As part of file upload (ASP.NET MVC3) adding id and enctype attributes to HTML.BeginForm return HttpPostedFileBase as null
Model:
public class ProfileModel
{
[UIHint("Upload")]
public HttpPostedFileBase ImageUpload { get; set; }
}`
ProfileForm.cshtml
@using (Html.BeginForm("Update", "Profile", new { ProfileId = ViewBag.ProfileID }, FormMethod.Post, new { @enctype = "multipart/form-data", @id = "ProfileForm" }))
{
<div>
@Html.LabelFor(model => Model.ImageUpload)
@Html.TextBoxFor(model => Model.ImageUpload, new { type = "file" })
</div>
<div class='buttons'>
<input type="submit" value='Save' />
</div>
}
Controller
public Upload(ProfileModel viewModel)
{
if (viewModel.ImageUpload != null && viewModel.ImageUpload.ContentLength > 0)
{
var uploadDir = "~/uploads";
var imagePath = Path.Combine(Server.MapPath(uploadDir), viewModel.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, viewModel.ImageUpload.FileName);
viewModel.ImageUpload.SaveAs(imagePath);
}
}
if I remove the @id = "ProfileForm"
attribute as below I am getting the HttpPostedFileBase (ImageUpload) value.
@using (Html.BeginForm("Update", "Profile", new { ProfileId = ViewBag.ProfileID }, FormMethod.Post, new { @enctype = "multipart/form-data"}))
{ }
I need to pass both id and enctype - can anyone please suggest me what I am doing wrong or is there any better way to do ?
I have fixed the issue by doing below: - When the submit is clicked I am positing the image first separately by calling below method