为什么asp.net MVC5中的模型绑定器的数据注释不起作用?

时间:2017-10-11 13:23:38

标签: c# asp.net-mvc web asp.net-mvc-5

我无法理解为什么模型绑定器不验证数据。没有模型绑定器我的代码工作正常。我试图调用的操作是Enter。所以,网址是这样的。 (本地主机:5×10 17 /客户/输入)。我的代码如下。

  

Customer Controller.cs

public class CustomerController : Controller
{
    // GET: Customer
    public ActionResult Load()
    {
        Customer obj = new Customer()
        {
            CustomerCode = "1001",
            CustomerName = "Rezwan"
        };
        return View("Customer", obj);
    }
    public ActionResult Enter()
    {
        return View("EnterCustomer");
    }

    public ActionResult Submit([ModelBinder(typeof(CustomerBinder))] Customer obj)
    {
        if (ModelState.IsValid)
            return View("Customer", obj);
        else
            return View("EnterCustomer");      
    }
}
  

EnterCustomer.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EnterCustomer</title>
</head>
<body>
    <div> 
        <form action="Submit" method="post">
            Customer Name - <input name="txtCustomerName" type="text" />
            Customer Code - <input name="txtCustomerCode" type="text" />
            <input id="Button1" type="submit" value="submit" />
         </form>
        @Html.ValidationSummary()
    </div>
</body>
</html>

  

Customer.cs

 public class Customer
{
    [Required]
    [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
    public string  CustomerCode { get; set; }

    [Required]
    [StringLength(10)]
    public string CustomerName { get; set; }
}
  

CustomerBinder.cs

 public class CustomerBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        HttpContextBase objContext = controllerContext.HttpContext;
        string CustCode = objContext.Request.Form["txtCustomerCode"];
        string CustName = objContext.Request.Form["txtCustomerName"];

        Customer obj = new Customer()
        {
            CustomerCode = CustCode,
            CustomerName = CustName
        };

        return obj;

    }
}
  

Customer.cshtml

@model HelloWorld.Models.Customer

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Customer</title>
</head>
<body>
    <div> 
        Name - @Model.CustomerName <br/>
        Code - @Model.CustomerCode
    </div>
</body>
</html>

请帮帮我。我是asp.net语言的新手。

1 个答案:

答案 0 :(得分:0)

这里真的没有必要创建自定义模型绑定器。你也反对很多mvc框架约定。您通常会看到一个操作对,如Create(Get)和Create(Post),其视图也是名称Create.cshtml

因此,在mvc中使用scaffolding框架,您可以从Customer模型类中生成所需的一切。

生成视图(Create.cshtml):

@model Scratch.Mvc.Models.Customer

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>View</title>
</head>
<body>
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Customer</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.CustomerCode, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CustomerCode, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.CustomerCode, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

在CustomerController中创建的控制器操作

    // GET: Customer/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Customer/Create
    [HttpPost]
    public ActionResult Create(Customer customer)
    {

        if (!ModelState.IsValid)
        {
            return View(customer);
        }

        //do work
        return RedirectToAction("Index");
    }

因此,post控制器操作采用Customer对象并使用默认的模型绑定器将html表单的字段与对象绑定。这是有效的,因为EditorFor将生成正确的html表单字段名称,这些名称将自动绑定到Customer类上的同一命名属性。

在POST操作中的ModelState检查然后返回包含验证信息的相同视图,然后使用ValidationMessageFor帮助器方法绑定。

它还会重定向回索引页面(此处未定义)以符合PRG模式。