即使文本框包含数据,所需的验证也会失败

时间:2018-08-28 14:20:03

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

我有一个搜索页面,其中有一个MyViewModel类作为其模型。我遇到一个问题,该字段突出显示为红色,因为[Required]属性中缺少数据,即使该字段确实具有值。

这是视图模型

public class MyViewModel
{
   [DisplayName("My Field")]
   [Required]
   public string MyField { get; set; }

   // This gets populated with search results from the database
   // whenever the user clicks the Search button and the page
   // posts back
   public List<Customer> SearchResults { get; set; }
}

这是ASP页面

@model MyProgram.MyViewModel

@using (Html.BeginForm("ListMyData", "Test", FormMethod.Get, htmlAttributes: new { @id = "search-form", @class = "form-horizontal" }))
{
   <div class="form-group">
      @Html.LabelFor(model => model.MyField, new { @class = "control-label col-sm-2" })
      <div class="col-sm-2">
         @Html.TextBoxFor(model => model.MyField, htmlAttributes: new { @class = "form-control" })
      </div>
   </div>
}

这是我的控制器

public class TestController
{
   // The first time that the user navigates to this page, the "else" clause
   // will execute and the form will get populated with default values.  When
   // the user clicks the "search" button, the view model will get populated
   // with database search results
   public ActionResult ListMyData(MyViewModel viewModel)
   {
      if (!string.IsNullOrEmpty(viewModel.MyField))
      {
         // Search database and return results
         /* viewModel.SearchResults = [data from database] */
      }
      else
      { 
         viewModel.MyField = "something";
      }

      return View("ListMyData", viewModel);
   }
}

“ something”值显示在页面上的文本框中,但文本框突出显示为红色。绝对是[Required]属性,因为如果删除[Required]属性,红色就会消失。

即使文本框中包含数据,为什么验证仍失败?

编辑:这是显示我的脚本的布局页面。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/DataTables/css/jquery.dataTables.css")
    @Scripts.Render("~/bundles/modernizr")
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
   @RenderBody()

   @Scripts.Render("~/bundles/jquery")
   @Scripts.Render("~/bundles/bootstrap")
   @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
   @Scripts.Render("~/Scripts/DataTables/jquery.dataTables.min.js")
   @RenderSection("scripts", required: false)
</body>
</html>

1 个答案:

答案 0 :(得分:1)

问题在于,您正在从ModelState接收到viewModel作为参数的验证(默认情况下没有任何值)。

解决此问题的一件事是通过在返回状态之前清除Model状态。

ModelState.Clear();
return View("ListMyData", viewModel);