[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
。我做错了什么?
答案 0 :(得分:1)
您不会为属性ImageUrl
呈现表单控件,只需呈现<label>
元素,因此当您提交时,ImageUrl
的值为null
且{{1由于ModelState
属性而无效。
包含属性的控件,以便在提交时将其值发送给控制器,例如
[Required]