I am writing an image upload form using ASP.NET MVC 3.
In the view, please notice that I am displaying @Model.ImagePath as text and as a @Html.TextBoxFor(model => model.ImagePath).
View:
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data" }))
{
@Html.HiddenFor(model => model.BannerSlideId)
@Html.HiddenFor(model => model.Key)
<p>
Image Path:@(Model.ImagePath)<br />
Image Path in TextBoxFor: @Html.TextBoxFor(model => model.ImagePath)
</p>
<p>
<label class="styled">Upload Slide Image</label>
<input type="file" name="image" />
</p>
<p>
<button type="submit">Save</button> @Html.ActionLink("Back to List", "Index")
</p>
}
I then select an image using the file input, and I submit the form to the Controller.
Controller action:
[HttpPost]
public ActionResult Create(BannerSlide model, HttpPostedFileBase image)
{
if (image != null)
model.ImagePath = image.FileName;
return View("Edit", model);
}
When I debug with a breakpoint, the image.FileName string is assigned to model.ImagePath. However, when I get back to the View I get Two different values from ImagePath.
Results
Image Path:@(Model.ImagePath)<br />
Correctly returns the image filename that was assigned. But,
Image Path in TextBoxFor: @Html.TextBoxFor(model => model.ImagePath)
Incorrectly returns blank!
Any ideas for why this is happening?
You should remove the ImagePath property from ModelState if you intend to modify it in your POST controller action or HTML helpers such as TextBoxFor will first look for a value inside ModelState when binding and then in the model: