I’m having problems getting an uploaded file (HTTPPostedFile) and an object posted to an action. I have a class called widget:
public class Widget
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FilePath { get; set; }
}
and in the Widget controller I have an ‘Add’ method
public ActionResult Add()
{
return View();
}
and an overloaded method to accept what the user posts back
[HttpPost]
public ActionResult Add(Widget widget, HttpPostedFile file)
{
// Save posted file using a unique
// Store the path/unique name in Widget.FilePath
// Save new Widget object
return View();
}
and in the View I have the following:
@model Project.Models.Widget
@{
using(Html.BeginForm())
{
Html.LabelFor(model => model.FirstName)<br />
Html.TextBoxFor(model => model.FirstName)<br />
Html.LabelFor(model => model.LastName)<br />
Html.TextBoxFor(model => model.LastName)<br />
<input type="file" id="file" /><br />
<input type="submit" value="Save" />
}
}
What I want to do is have the user fill out the form and select a file to upload. Once the file is uploaded, I want to save the file off using a unique name and then store the path of the file as widget.FilePath.
Each time I try, the widget object is populated, but the uploadedFile is null.
Any Help would be greatly appreciated.
There are a couple of issues with your code.
enctype="multipart/form-data"to your form, otherwise you won’t be able to upload any files.nameattribute and that the value of this attribute matches the name of your action argument. Assigning anidhas no effect for the server side binding.For example:
Also make sure that your controller action works with a
HttpPostedFileBaseinstead ofHttpPostedFile:Also you could merge the 2 parameters into a single view model:
and then:
Finally read the following blog post: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx