Вы должны добавить новый { enctype="multipart/form-data"}
в форму, чтобы разрешить загрузку файла.
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
Измените код cshtml на:
@using (Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(model => model.userImageUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageFile" />
@Html.ValidationMessageFor(model => model.userImageUrl, "", new { @class = "text-danger" })
</div>
</div>
}
и переместите эту строку кода внутри if user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
в этом случае file.FileName
может быть нулевым.
if(file !=null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string imgPath = Path.Combine(Server.MapPath("~/User_Images/"), fileName);
file.SaveAs(imgPath);
user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
}
Еще одно примечание, которое требует изменения parameter name
в действии, аналогично name of input
тип файла:
<input type="file" name="ImageFile" /> to <input type="file" name="file" />