在Controller [ASP.Net MVC]中动态检查验证

时间:2018-10-08 07:10:30

标签: asp.net-mvc validation model controller modelstate

我正在为Travels门户开发MVC应用程序。在这里,我有一个表单来提交新的旅行请求,我的控制器看起来像这样

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(CreateOrEditCabBookingDto model)
{
    if (ModelState.IsValid)
    {
        CabBookingAppService.Instance.CreateOrUpdate(model);
    }
    return PartialView("_CreateOrUpdateCabBooking", model);
}

我没有在我的模型中包含任何验证注释,因为我希望它们根据某些条件动态执行。是否可以在控制器中动态进行验证并将其添加到模型状态

示例:基于 StatusId 属性值,将 StartDate 设置为必需。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(CreateOrEditCabBookingDto model)
{
    if (ModelState.IsValid)
    {
        If(model.StatusId == 10)
        {
           // Check validation here
           // Property "StartDate" is Required
        }

        CabBookingAppService.Instance.CreateOrUpdate(model);
    }
    return PartialView("_CreateOrUpdateCabBooking", model);
}

根据输入,我进行了如下更改:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(CreateOrEditCabBookingDto model)
{
    if (string.IsNullOrEmpty(model.FromDateTime))
    {
       ModelState.AddModelError("FromDateTime","Date is Required");
    }

    if (ModelState.IsValid)
    {
        CabBookingAppService.Instance.CreateOrUpdate(model);
    }
    return PartialView("_CreateOrUpdateCabBooking", model);
}

“我的视图”看起来像这样:

 @using (Ajax.BeginForm("CreateOrEdit", "Travel", null, new AjaxOptions
 {
     HttpMethod = "POST",
     OnSuccess = "OnSuccess",
     OnBegin = "OnBegin",
     InsertionMode = InsertionMode.Replace,
     UpdateTargetId = "PopupId"
 }, new { id = "frm" }))
 {
    ............................
    <div class="form-group col-md-3">
       @Html.LabelFor(model => model.FromDateTime)
       @Html.TextBoxFor(model => model.FromDateTime, new { @class = "form-control datetimepicker", autocomplete = "off" })
       @Html.ValidationMessageFor(model => model.FromDateTime)
     </div>
     ............................
 }

0 个答案:

没有答案