代码之家  ›  专栏  ›  技术社区  ›  Steve Horn

返回空值的ASP.Net MVC模型绑定

  •  2
  • Steve Horn  · 技术社区  · 17 年前

    给定以下标记:

     <form method="post" action="/home/index">
        Username:
        <%= Html.TextBox("UserName")%>
        Password:
        <%= Html.TextBox("Password")%>
        <input id="login" type="button" value="Login" />
        <input id="Submit1" type="submit" value="submit" />
     </form>
    

    你能告诉我为什么调用我的操作时模型绑定不起作用吗

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string UserName, string Password)
        {
            //UserName and Password are null!  Why?            
        }
    

    表单值正在过帐。如果我检查Request.Form属性,就会看到正确的值正在被发布。

    ? 请求表单 [System.Web.HttpValueCollection]:{UserName=sdf&Password=sdf} 基{System.Collections.Specialized.NameObjectCollectionBase}:{UserName=sdf&Password=sdf} 所有键:{string[2]}

    5 回复  |  直到 17 年前
        1
  •  1
  •   Chuck Conway    17 年前

    是否尝试将Bind属性添加到参数中?

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index([Bind]string UserName, [Bind]string Password)
    {
        //UserName and Password are null!  Why?            
    }
    
        2
  •  1
  •   Lance Fisher    16 年前

    我有一个类似的问题,结果是由于字段的命名。

    <form method="post" action="/company/update/3">
       Name:
       <%= Html.TextBox("Company.Name")%>
       FEIN:
       <%= Html.TextBox("FEIN")%>
    
       <input type="submit" value="submit" />
    </form>
    

    邮寄至:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(int id, Company company)
    {
        //Company.FEIN is null!
    }
    

    如果Company.Name是发布的第一个值,则似乎会发生这种情况。

        3
  •  0
  •   Mike Geise    17 年前

    史蒂夫我有一个类似的问题,我发现这是因为我有我的模型的属性键和值,模型绑定器不喜欢。

    尝试将用户名更改为用户和密码,以查看是否存在问题。

        4
  •  0
  •   UpTheCreek    17 年前

    运行此命令时,可以尝试将调试器附加到MVC源代码,以查看引擎盖/引擎盖下发生了什么。

        5
  •  0
  •   Sandip - Frontend Developer    10 年前

    请将name属性添加到控件(Html.TextBox(“UserName”))