Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
i want to upload my picture to my host and save url'picture to database

in my table on database i have this fileds:
id
title
imageurl

and i write this code for action:
C#
[HttpGet]
       public ActionResult Create()
       {
           return View();
       }
       [HttpPost]
       public ActionResult Create(HttpPostedFileBase ImageFile, TNew tnew)
       {
           if(ImageFile!=null && ImageFile.ContentLength>0)
           {
               var file = Path.GetFileName(ImageFile.FileName);
               var pathfile = Path.Combine(Server.MapPath("~/Photo"), file);
               ImageFile.SaveAs(pathfile);
               tnew.imageurl = pathfile;
               _db.TNews.Add(tnew);
               _db.SaveChanges();
           }

           return View();
       }


and this for create page:
HTML
@using (Html.BeginForm("Create", "HOME", FormMethod.Post, new {enctype="mulipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>TNew</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.title)
            @Html.ValidationMessageFor(model => model.title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.imageurl)
        </div>
        <div class="editor-field">
            <input type="file" name="ImageFile" />
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

but when i submit my form image file is null
how can i solve this?
Posted

1 solution

You are Mispelled enctype in Form Tag that's why posted file always be null

Your Code
C#
@using (Html.BeginForm("Create", "HOME", FormMethod.Post, new {enctype="mulipart/form-data" }))


Corrected Code
@using (Html.BeginForm("Create", "HOME", FormMethod.Post, new { enctype = "multipart/form-data" }))


Hope this helps
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900