Model State为false,错误消息显示ImageUrl为null .....这里是控制器代码和视图

时间:2015-01-29 06:03:09

标签: asp.net-mvc asp.net-mvc-5

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="ArticleId,ArticleAuthorId,IsActive,Name,Desription,ImageUrl")] ArticleDM articledm)
{
  var errors = ModelState
               .Where(x => x.Value.Errors.Count > 0)
               .Select(x => new { x.Key, x.Value.Errors })
               .ToArray();

  if (ModelState.IsValid)
  {
    articledm.ArticleId = Guid.NewGuid();
    db.Article.Add(articledm);                  
    HttpPostedFileBase ArtImgUrl = Request.Files["ArtImgUrl"];
    if (ArtImgUrl != null && ArtImgUrl.ContentLength > 0)
    {
      string fileDatetime = Convert.ToString(System.DateTime.Now.Month
        + "" + System.DateTime.Now.Day + "" 
        + System.DateTime.Now.Year + "" + System.DateTime.Now.Hour + "" 
        +  System.DateTime.Now.Minute + "" + System.DateTime.Now.Second);
      string fileName = ArtImgUrl.FileName;
      articledm.ImageUrl = "~/ArticleImages/" + fileDatetime + fileName;
      ArtImgUrl.SaveAs(Server.MapPath("~/ArticleImages/" + fileDatetime + fileName));
  }     
  db.SaveChanges();
  return RedirectToAction("Index");
}

并且查看代码是

 @Html.LabelFor(model => model.ArticleAuthorId, "ArticleAuthorId", new { @class = "control-label col-md-2" })
 <div class="form-group">
   @Html.LabelFor(model => model.ImageUrl, new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    <input type="file" name="ArtImgUrl" id="file" />
  </div>
</div>

,模型是

public class ArticleDM : ArticleImage
{
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key]
  public Guid ArticleId { get; set; }
  [ForeignKey("ArticleAuthor")] [Column(Order = 1)]
  public Guid ArticleAuthorId { get; set; }
  public ArticleAuthorDM ArticleAuthor { get; set; }
  public bool IsActive { get; set; }
}

public class ArticleImage
{
  public ArticleImage();
  [Required]
  public string Desription { get; set; }
  [Required]
  public string ImageUrl { get; set; }
  [Required]
  public string Name { get; set; }
}

Model.state = false,调试时的错误代码显示ImageUrl值= null。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您不会为属性ImageUrl呈现表单控件,只需呈现<label>元素,因此当您提交时,ImageUrl的值为null且{{1由于ModelState属性而无效。

包含属性的控件,以便在提交时将其值发送给控制器,例如

[Required]