我的部分视图未显示验证错误,也显示错误我的两个视图都被打开了

时间:2013-05-03 03:27:54

标签: asp.net-mvc asp.net-mvc-4 razor

我在两个部分视图中面临验证问题

_partialA.cshtml

@model demo3.Models.ModelA

   @using (Html.BeginForm("TEST", "Home"))    {

<h2>_partialA</h2>
<div>
     @Html.EditorFor(m => m.EmployeeId)  
     @Html.ValidationMessageFor(m => m.EmployeeId) 
</div>
<div>
     @Html.EditorFor(m => m.EmployeeName)
     @Html.ValidationMessageFor(m => m.EmployeeName) 
</div>
 <input class="mainbutton" type="submit" value="TEST"/><br />
 }

另一个局部视图就是这个

_partialB.cs.html

 @model demo3.Models.ModelB
      @using (Html.BeginForm("CreateAgreement", "Home"))
            {

<h2>_partialB</h2>
<div>
    @Html.EditorFor(m => m.Comapny)
    @Html.ValidationMessageFor(m => m.Comapny)
</div>
<div>
    @Html.EditorFor(m => m.FisacalYear)
    @Html.ValidationMessageFor(m => m.FisacalYear)  </div>
  <input class="mainbutton" type="submit" value="CreateAgreement"/><br />
 }

这是我的控制器代码

 [HttpPost]
    public ActionResult CreateAgreement(ModelB modelb)
    {
        if (ModelState.IsValid)
        {
            return View("Start", modelb);
        }
        return View("Start", modelb);
    }
    [HttpPost]
    public ActionResult TEST(ModelA modela)
    {
        if (ModelState.IsValid)
        {
            return View("Start", modela);
        }
        return View("Start", modela);
    }
    public ActionResult Start()
    {
        return View();
    }
    public ActionResult FirstView()
    {
        ModelA objA = new ModelA();
        return PartialView("_partialA", objA);
    }
    public ActionResult SecondView()
    {
        ModelB objB = new ModelB();
        return PartialView("_partialB", objB);
    }

现在我没有收到任何关于点击按钮的错误消息......另一件事......我的两个视图都被打开了......点击按钮..如何防止这种情况?

1 个答案:

答案 0 :(得分:1)

要验证表单,请检查以下步骤:

1)在部分视图中将布局设置为null

@{
    Layout = null;
}

2)在表单前添加这些脚本:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>

@using (Html.BeginForm("CreateAgreement", "Home"))
 {

3)添加Html验证:

@using (Html.BeginForm("CreateAgreement", "Home"))
 {
     @Html.ValidationSummary(true)

4)如果您的模型中有注释并且错误消息可以使用。