Question

I have an mvc 4 project where i need to write data to a database including an image in the 'create' view.

I found a few examples on how to upload an image. But none of the examples had some extra input fields along together with the html file upload control.

Makes me wonder if it's possible to browse to the image and fill in the other fields and press 'send' button, and receive all the data in the controller and this method in particular:

 [HttpPost]
 public ActionResult Create(FormCollection formCollection) 
 { 
  foreach (var key in formCollection.AllKeys)
  {
     if (key == "file")
     {
        foreach (string s in Request.Files)
        {
           HttpPostedFileBase file = Request.Files[s];
           if (file.ContentLength > 0)
           {
           }
        }
      }
   }
}

This is the view:

 @using (Html.BeginForm("Create", "Item", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Item</legend>

        <div class="editor-label">
            Description:
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
         <div class="editor-label">
            Image:
        </div>

        <input type="file" name="file" id="file" />

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

Request.Files is always empty in this case.

What am I missing?

Was it helpful?

Solution

You should also be able to do this using a strongly-typed edit model:

public class MyDataEditModel
{
    public string Description { get; set; }
    public HttpPostedFileBase File { get; set; }
}


[HttpPost]
public ActionResult Create(MyDataEditModel model) 
{ 
    // is model.File null here?  
}

OTHER TIPS

You can follow this tutorial which shows how to upload an image in ASP.NET MVC

Here in the action as shown below.

[HttpPost]
public ActionResult Index(UserModel model, HttpPostedFileBase file)
{}

along with the file posted, a UserModel is also posted which gets the other data from the page, which is what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top