我想编辑用户详细信息,同时使用相同的按钮上传照片,但在我尝试保存文件时,HttpPostedFileBase
始终为空。
图片模型
public class Image
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[HiddenInput(DisplayValue = false)]
[Key]
public Guid ID { get; set; }
public string UserID { get; set; }
public int ImageSize { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
public string FilePath { get; set; }
public int Counter { get; set; }
[Required(ErrorMessage = "Please select file")]
public HttpPostedFileBase File { get; set; }
public virtual ApplicationUser ApplicationUsers { get; set; }
public virtual Job Jobs { get; set; }
}
ParentViewModel
public class ImgAndUser
{
public EditUserViewModel EditUser { get; set; }
public Image EditImage { get; set; }
}
编辑控制器:
[HttpPost]
public async Task<ActionResult> Edit(ImgAndUser IU, HttpPostedFileBase file)
{
if (file != null && IU.EditImage.File.ContentLength > (2 * 1024 * 1024))
{
ModelState.AddModelError("Custom Error", "File must be less than 2 MB or doesn't exist");
return View();
}
else if(!(IU.EditImage.File.ContentType == "image/jpeg" || IU.EditImage.File.ContentType == "image/gif" || IU.EditImage.File.ContentType == "image/jpg"))
{
ModelState.AddModelError("CustomError", "Only jpeg and gif formats");
return View();
}
else
{
string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
string path = HttpContext.Server.MapPath("~/FilesDB/Images");
file.SaveAs(Path.Combine(Server.MapPath("~/FilesDB/Images"), fileName));
IU.EditImage.ID = Guid.NewGuid();
IU.EditImage.FileName = IU.EditImage.File.FileName;
IU.EditImage.ImageSize = IU.EditImage.File.ContentLength;
byte[] data = new byte[IU.EditImage.File.ContentLength];
IU.EditImage.File.InputStream.Read(data, 0, IU.EditImage.File.ContentLength);
IU.EditImage.ImageData = data;
IU.EditImage.UserID = LoggedUserId;
IU.EditImage.FilePath = path;
}
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(IU.EditUser.Id);
if (user == null)
{
ModelState.AddModelError("", "User not found");
}
else
{
user.Email = IU.EditUser.Email;
user.Name = IU.EditUser.Name;
user.Surname = IU.EditUser.Surname;
user.City = IU.EditUser.City;
user.ZIP = IU.EditUser.ZIP;
user.Street = IU.EditUser.Street;
user.Nr = IU.EditUser.Nr;
user.CompName = IU.EditUser.CompName;
user.CUI = IU.EditUser.CUI;
user.DescCompany = IU.EditUser.DescCompany;
try
{
//collect all images except final one
var existImgRows = context.Images.Where(x => x.UserID == LoggedUserId).OrderByDescending(x => x.ID).Skip(0).Select(x => x);
if (existImgRows != null)
{
foreach (var item in existImgRows)
{
context.Entry(item).State = System.Data.Entity.EntityState.Deleted;
}
}
context.Entry(IU.EditImage).State = System.Data.Entity.EntityState.Added;
context.SaveChanges();
return RedirectToAction("Details", "Jobs", new { controller = "JobsController", action = "Details", id = Session["DetailsURL"] });
}
catch (DbEntityValidationException ex)
{
foreach (var validationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Console.WriteLine("Property: {0} throws Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
}
ModelState.AddModelError("", "Something failed");
return View();
}
在else { }
语句string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
中,参数file
为null
,但if语句与我在浏览器中选择的文件数据一起传递。
修改视图
@using (Html.BeginForm("Edit", "ImgAndUser", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => Model.EditUser.Id)
<div class="form-group">
@Html.LabelFor(m => Model.EditUser.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => Model.EditUser.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => Model.EditUser.Email, "", new { @class = "text-danger" })
</div>
</div>
.
.
Losts of stuff similar with above.
.
.
</div>
@Html.ValidationSummary(true)
@Html.HiddenFor(model => Model.EditImage.ID);
<table>
<tr>
<td>Select File : </td>
<td>
@Html.TextBoxFor(Image => Model.EditImage.File, new { type = "file" })
@Html.ValidationMessage("CustomError")
</td>
<td>
<input type="submit" value="Save" />
</td>
</tr>
</table>
}