代码之家  ›  专栏  ›  技术社区  ›  Somebody

模型状态。是否仅在定义操作中的对象时有效?

  •  0
  • Somebody  · 技术社区  · 9 年前

    我刚开始学习MVC,所以这可能是一个愚蠢的问题。

    查看数据注释以执行验证,我注意到 ModelState.IsValid 仅当对象在Action中定义如下时,属性名称也必须与输入名称匹配:

    客户控制器.cs

    public ActionResult Submit(Customer obj) <-- here
    {
        //Customer obj = new Customer();
        //obj.CustomerName = Request.Form["CustomerName"];
        //obj.CustomerCode = Request.Form["CustomerCode"];
    
        if (ModelState.IsValid)
        {
             return View("Customer", obj);
        }
        else
        {
             return View("EnterCustomer");
        }            
    }
    

    客户.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace MyFirstWebApp.Models
    {
        public class Customer
        {
            [Required]
            [StringLength(10)]
            public string CustomerName { get; set; }
    
            [Required]
            [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
            public string CustomerCode { get; set; }
        }
    }
    

    输入Customer.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="CustomerName" type="text" /> <br />
                @Html.ValidationMessageFor(x => x.CustomerName) <br />
                Customer Code: <input name="CustomerCode" type="text" /> <br />
                @Html.ValidationMessageFor(x => x.CustomerCode) <br />
                <input id="Submit1" type="submit" value="submit" />
            </form>
        </div>
    </body>
    </html>
    

    但如果我将obj定义如下,ModelState。当我输入无效值以执行验证时,IsValid始终为真,有人能告诉我为什么吗?

    客户控制器.cs

    public ActionResult Submit()
    {
        Customer obj = new Customer();
        obj.CustomerName = Request.Form["CustomerName"];
        obj.CustomerCode = Request.Form["CustomerCode"];
    
        if (ModelState.IsValid)
        {
             return View("Customer", obj);
        }
        else
        {
             return View("EnterCustomer");
        }            
    }
    
    1 回复  |  直到 9 年前
        1
  •  4
  •   JamieD77    9 年前

    您可以在Controller中使用TryValidateModel来验证模型。

    Customer obj = new Customer();
    obj.CustomerName = Request.Form["CustomerName"];
    obj.CustomerCode = Request.Form["CustomerCode"];
    
    if (TryValidateModel(obj))
    {
         return View("Customer", obj);
    }
    else
    {
         return View("EnterCustomer");
    }