在MVC3中单击按钮之前验证将触发

时间:2014-07-15 08:30:39

标签: c# asp.net-mvc-3 partial-views model-validation

我是MVC3的新手。如果有任何问题没有达到标记,请忽略。

我有部分视图名称“_LikeFilter”。此视图中包含文本框。

这是LikeFilterModel。

public class LikeFilterModel
{
  [Required]
  public string SearchText { get; set; }
}

_LikeFilter查看

@model PMEX.CSR.Models.LikeFilterModel
@{
Layout = null;
 }
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">   </script>
  <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<div align="center">
<div class="editor-label">
    @{
        Html.LabelFor(m => m.ReportName);
    }
    <div>
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>
                    Search By Name :
                </td>
                <td>
                    @Html.TextBoxFor(m => m.SearchText, new { @class = "editor-field" })
                    @Html.ValidationMessageFor(m => m.SearchText)
                </td>
            </tr>
        </table>
  </div>

这是我的报告视图,调用_LikeFilter Partail视图。

@{
  using (Html.BeginForm())
    {

    <div align="center">
           <div>

                @{
        // calling partial view
        Html.RenderAction("GetCommodityReportFilter", "LikeFilter"); 

                }
            </div>
            <div>
                <input type="submit" value="Display" />
            </div>

    </div>     
    }
  }

LikeFilterController类

 Public class LikeFilterController 
 {
    [ChildActionOnly]
    public ActionResult GetCommodityReportFilter(LikeFilterModel modelObj)
    {
        LikeFilterModel model = null;
        if (Request.HttpMethod != "POST")
        {
            model = new LikeFilterModel();
            model.ReportName = ReportType.Commodity;
        }
        else
            model = modelObj;

        return GetLikeFilter(model);
    }




 private ActionResult GetLikeFilter(LikeFilterModel modelObj)
    {
        LikeFilterModel model = modelObj;
        model.ReportName = modelObj.ReportName;
        model.ReportStatuses = GetStatuses();
        ViewBag.LikeFilterAttributes = model;
        return View("_LikeFilter", model);
    }

   }

当我的页面出现时出现问题它显示错误消息“SearchText是必需的”

我希望在文本框中的某些输入或按钮单击后进行此验证。不是第一次出现页面时。

1 个答案:

答案 0 :(得分:0)

这是因为模型绑定导致验证触发。 您需要清除模型状态。

 [ChildActionOnly]
    public ActionResult GetCommodityReportFilter(LikeFilterModel modelObj)
    {
        LikeFilterModel model = null;
        if (Request.HttpMethod != "POST")
        {
            ModelState.Clear(); // add this
            model = new LikeFilterModel();
            model.ReportName = ReportType.Commodity;
        }
        else
            model = modelObj;

        return GetLikeFilter(model);
    }