繁体   English   中英

数据注释验证在ASP.NET MVC 3中不起作用

[英]Data Annotation Validation not working in ASP.NET MVC 3

我在Partial视图中有一个表单,该表单呈现在选项卡控件的选项卡中,如下所示:

@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; }
    }

该模型永远不会得到验证,并直接在控制器上的事务中运行。 为什么这不起作用?

我建议首先检查您是否以正确的顺序包含了必要的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 });
}

您需要显式检查操作中是否为ModelState.IsValid ,如果不是,请返回到编辑视图。
如果显示无效模型的编辑视图,则MVC将通过Validate帮助器自动显示错误消息。

这应该说明一些问题: NerdDinner的ASP.NET MVC中有效的ModelState.IsValid是什么?

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

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

并参考此链接以获取更多详细信息。 如何:使用DataAnnotations属性验证模型数据

好的,问题是Telerik脚本注册器未引用正确的JQuery。 现在正在工作。 我直接引用了JQuery库,还有验证脚本。 在Telerik脚本Registrar上,它已经是默认组的一部分,像我在做的那样重新引用它们,导致它出于某种原因而疯狂。 仅添加对脚本的引用,这些引用不属于原始默认组。 有关此的更多信息,需要阅读此MVC扩展的在线文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM