我有一个表格" MovieForm"用于将电影添加到数据库。当我填写所有必需的输入并按下保存按钮时,电影正常添加到数据库。如果我先将一个或多个必需输入留空,然后按save,我会收到DataAnnotations错误消息," ModelState.isValid"变得虚假,并将我重新定向到我已经使用此代码的相同形式:
[HttpPost]
public ActionResult Save(Movie movie)
{
if (!ModelState.IsValid)
{
return View("MovieForm");
}
//logic for saving movie
}
以及它应该如何完成。此操作后会出现问题。现在,当我填写所有必需的输入并再次按下保存按钮时,ModelState.IsValid没有更新,它仍然是假的,所以我陷入了这个if语句。
如何重置它,以便再次检查是否符合要求?
型号:
public class Movie
{
[Key]
public Guid MovieID { get; set; }
[Required]
[StringLength(40)]
public string Title { get; set; }
[Required]
[StringLength(60)]
public string Director { get; set; }
[Required]
[StringLength(256)]
public string Actors { get; set; }
}
查看
@using Cinema.Models
@model Cinema.Models.Movie
@using (Html.BeginForm("Save", "Movies", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<div class="form-group">
@Html.LabelFor(m => m.Title, "Title", new { @class = "col-md-2 control-label" })
<div class="col-md-8">
@Html.TextBoxFor(m => m.Title, new { @class = "form-control col-md-4" })
@Html.ValidationMessageFor(m => m.Title, "", new { @class = "text-danger col-md-4 form-control-static" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Director, "Director", new { @class = "col-md-2 control-label" })
<div class="col-md-8">
@Html.TextBoxFor(m => m.Director, new { @class = "form-control col-md-4" })
@Html.ValidationMessageFor(m => m.Director, "", new { @class = "text-danger col-md-4 form-control-static" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Actors, "Actors ", new { @class = "col-md-2 control-label" })
<div class="col-md-8">
@Html.TextBoxFor(m => m.Actors, new { @class = "form-control col-md-4" })
@Html.ValidationMessageFor(m => m.Actors, "", new { @class = "text-danger col-md-4 form-control-static" })
</div>
</div>
@Html.HiddenFor(m => m.MovieID)
<div class="form-group">
<div class="col-md-offset-2 col-md-4">
<input type="submit" class="btn btn-default" value="Save" />
<a class="col-md-offset-1" href="/Movies/">cancel</a>
</div>
</div>
}
答案 0 :(得分:0)
您可以通过在调试模式下扩展它来检查ModelState对象中的错误
答案 1 :(得分:0)
Stephen's suggestion in his comment gives a very nice succinct way of filtering the ModelState to see what is causing errors. I did something similar (though rather longer winded) to combine them in a single string for easy viewing/copying/pasting. Try adding this to your controller:
string modelErrors = GetModelStateErrors(ModelState);
That calls this method:
public string GetModelStateErrors(ModelStateDictionary ms)
{
StringBuilder errors = new StringBuilder();
foreach (string k in ms.Keys)
{
if (ms[k].Errors.Count > 0)
{
errors.Append($"\n{k}:\n");
foreach (var e in ms[k].Errors)
{
errors.Append($" {e.ErrorMessage}\n");
}
}
}
return errors.ToString();
}