我正在尝试在数据库中保存图像路径,并在文件系统中保存实际图像。文件被完美复制但它的源不会被插入到数据库中,它在ModelState.IsValid
函数中始终为空
这是我的电影课
public class Movie
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int MovieId { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Genre is required")]
public string Genre { get; set; }
[Required(ErrorMessage = "Rating is required")]
public int Rating { get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
[Required(ErrorMessage = "Date is required")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
[Required(ErrorMessage = "Image is required")]
public string ImageSource { get; set; }
}
这是我的创建视图
@using (Html.BeginForm("Create","Movies",FormMethod.Post,new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Genre)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Genre)
@Html.ValidationMessageFor(model => model.Genre)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
@Html.ValidationMessageFor(model => model.Rating)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ImageSource)
</div>
<div class="editor-field">
<input type="file" name="uploadImages" multiple="multiple" class="input-files" />
@Html.ValidationMessageFor(model => model.ImageSource)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
这是我的行动方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Movie movie)
{
foreach (string file in Request.Files)
{
var postedFiles = Request.Files[file];
postedFiles.SaveAs(Server.MapPath("~/Content/Images/") + Path.GetFileName(postedFiles.FileName));
}
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
ImageSource
始终为null,并导致一个或多个实体出现验证错误。
答案 0 :(得分:0)
您没有在任何地方分配ImageSource,要么从模型中删除ImageSource并使用文件名(或完整路径)将其写入数据库。
或使用javascript将文件名分配给ImageSource。
编辑:或者只是从ImageSource中删除Required属性。