数据注释验证不是ASP.NET MVC 3个工作(Data Annotation Validatio

2019-10-16 22:57发布

我有一个上看起来像这样的选项卡控件选项卡中渲染的局部视图内的一种形式:

@model USARAFSyncMVC.Areas.Event.Models.EventFullScaffoldModel

@using (Ajax.BeginForm("SaveMainEventDetails", "Event", new { area = "Event" },
    new AjaxOptions { UpdateTargetId = "FormWrapper", OnComplete = "SetSuccessLabel", InsertionMode = InsertionMode.Replace },
    new { method = "post" }))
{
    @Html.Hidden("eventType", "1", new { id = "eventType" })
    <div id="FormWrapper">
      <hr />
      <table border="0">
        <tr>
          <td>Title</td>
          <td>@Html.TextBoxFor(model => model.Title, new { style = "width:300px" })
            @Html.ValidationMessageFor(model => model.Title)</td>

        </tr>
        <tr>
          <td>OPR</td>
          <td> @Html.EditorFor(model => model.OPRID)</td>

        </tr>
        <tr>
          <td>Organization</td>
          <td> @Html.EditorFor(model => model.DomainID)</td>

        </tr>
        <tr>
          <td>POC</td>
          <td> @Html.EditorFor(model => model.POC)</td>

        </tr>
        <tr>
          <td>Location</td>

          <td>
            @Html.EditorFor(model => model.LocationID)
          </td>

        </tr>
        <tr>
          <td>Dates</td>
          <td>
            <table>
              <tr>
                <th>@Html.LabelFor(m => m.StartDate)</th>
                <th> @Html.LabelFor(m => m.EndDate)</th>
              </tr>
              <tr>
                <td> @Html.EditorFor(m => m.StartDate)</td>
                <td>@Html.EditorFor(m => m.EndDate)</td>
              </tr>

            </table>

            <table id="DeployRedeployDiv">
              <tr>
                <th>Deploy</th>
                <th>ReDeploy</th>
              </tr>
              <tr>
                <td> @Html.EditorFor(m => m.EstimatedDeployDate)</td>
                <td>@Html.EditorFor(m => m.EstimatedReDeployDate)</td>
              </tr>

            </table>

          </td>
        </tr>
        <tr>
          <td>OSRs</td>
          <td>
            @(Html.Telerik()
                  .PanelBar()
                  .Name("PanelBar")
                  .HtmlAttributes(new { style = "width:300px;" })
                  .Items(o => o.Add().Text("Click").Content(@<text> 

                @Html.CheckBoxList("OprList",
                    x => x.OprList,
                    x => x.OPRID,
                    x => x.AltTitle,
                    x => x.EventOSRs, Position.Vertical)</text>).Expanded(false)))
          </td>
        </tr>
        <tr>
          <td>Purpose</td>
          <td> @Html.TextBoxFor(model => model.Why, new { style = "width: 400px; height:200px" })</td>
        </tr>
        <tr>
          <td>Background</td>
          <td> @Html.TextBoxFor(model => model.What, new { style = "width: 400px; height:200px" })</td>
        </tr>
        <tr>
          <td>Viewable</td>
          <td> @Html.CheckBoxFor(model => model.Viewable)</td>
        </tr>

      </table>
      <div>
        <input class="t-button" type="submit" name="button" value="Save" />

      </div>

    </div>

}

这里是控制器:

    [HttpPost]
    public ActionResult SaveMainEventDetails(EventFullScaffoldModel model, string[] OprList, string eventType, string cbLoc, string cbOpr, string cbOrg)
    {
        if (OprList != null)
        {
            model.EventOSRs = miscRepository.GetOprsList().ToModel().Where(o => OprList.Contains(o.OPRID.ToString())).ToList();
        }

        model.Type = int.Parse(eventType);
        model.LocationID = cbLoc;
        model.OPRID = int.Parse(cbOpr);
        model.DomainID = int.Parse(cbOrg);
        eventRepository.Insert(model.ToDto());
        return View();
    }

这里是型号:

   public partial class EventFullScaffoldModel
    {
        public Int32 EventID { get; set; }

        [Required(ErrorMessage = "Required!")]
        public String Title { get; set; }

        [Required(ErrorMessage = "Required!")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
        public DateTime StartDate { get; set; }

        [Required(ErrorMessage = "Required!")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
        public DateTime EndDate { get; set; }

        [Required(ErrorMessage = "Required!")]
        public String What { get; set; }

        [Required(ErrorMessage = "Required!")]
        public String Why { get; set; }

        public Nullable<DateTime> Modified { get; set; }

        public String ModifiedBy { get; set; }

        public Nullable<DateTime> Created { get; set; }

        public String CreatedBy { get; set; }

        [UIHint("ActiveDirectoryLoadOnDemand"), Required]
        public String POC { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}")]
        public Nullable<DateTime> EstimatedDeployDate { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}")]
        public Nullable<DateTime> EstimatedReDeployDate { get; set; }

        public Nullable<Int32> TSCMISID { get; set; }

        public Nullable<Int32> ReviewStatus { get; set; }

        public int? Type { get; set; }

        public String InactivityReason { get; set; }

        public Boolean Viewable { get; set; }

        public string OPRAltTitle { get; set; }

        [UIHint("OprDropDown"), Required]
        public int OPRID { get; set; }

        [UIHint("OrgDropDown"), Required]
        public int DomainID { get; set; }

        [UIHint("LocationsLoadOnDemand"), Required]
        public string LocationID { get; set; }

        public string LocationTitle { get; set; }

        public IList<OsrModel> EventOSRs { get; set; }

        public IList<TargetAndEffectModel> EventTargetEffects { get; set; }

        public IList<AssociationModel> EventAssociations { get; set; }

        public IList<EventObjectiveModel> EventObjectives { get; set; }

        public IList<StrategicObjectiveModel> EventTSOs { get; set; }

        public IList<TaskModel> EventTasks { get; set; }

        public IList<PaxModel> EventPaxBreakDowns { get; set; }

        public IList<FundingModel> EventFundings { get; set; }

        public IList<UnitModel> EventExecutingUnits { get; set; }

        public IList<OsrModel> OprList { get; set; }

        public IList<ObjectiveModel> ObjectiveList { get; set; }

        public IList<StrategicObjectiveModel> StrategicList { get; set; }

        public IList<OrgModel> OrgsList { get; set; }
    }

模型从来没有得到验证,并直接通过控制器上的事务中运行。 这是为什么不工作?

Answer 1:

我建议首先检查是否已包括了不显眼的验证所需的JavaScript文件,以正确的顺序,这将让验证在客户端成功地发生。

关于服务器端验证对方告诉基本上你必须明确地检查,模型保存到数据库ModelState.IsValid 。 既然你正在一个AJAX调用我可以建议你JSON返回模型的状态误差。

所以在OnFailure的方法AjaxOptions您可以解析JSON并作为一个div摘要显示错误。

基本上,你可以按照这个模式。

[HttpPost]
public JsonResult SaveMainEventDetails(..)
{
  if(ModelState.IsValid)
  {
    .. save to database

    return Json(new{ success = true });
  }

  var errorDict =  ModelState..
  return Json(new { success = false, errors = errorDict });
}


Answer 2:

你需要明确检查是否ModelState.IsValid的动作,并返回到编辑视图,如果它不是。
如果你表现出编辑视图无效的模式,MVC会自动显示经过验证助手的错误消息。



Answer 3:

这应该提供一些线索: 什么是ASP.NET MVC中的NerdDinner ModelState.IsValid有效?

基本上,你必须使用触发模型验证ModelState.IsValid



Answer 4:

添加@{ Html.EnableClientValidation(); } @{ Html.EnableClientValidation(); }在查看

并参考有关详细信息,thsi链接如何:验证模型数据使用DataAnnotations属性



Answer 5:

好的问题是Telerik的脚本书记官长引用不正确的JQuery。 现在,这是工作。 我是直接引用了jQuery库,也验证脚本。 在Telerik的脚本注册处处长,它已经是缺省组的一部分重新引用他们为我所做的一切,导致其崩溃了出于某种原因。 只引用添加脚本没有拆开原来的默认组。 有关更多的信息,需要阅读本MVC扩展的在线文档。



文章来源: Data Annotation Validation not working in ASP.NET MVC 3