2012-09-14 34 views
0

通过我的代码后,我已验证collection.Get(“username”);在下面的代码中是null,这意味着我的post参数只是没有进入控制器。任何人都可以发现问题吗?为什么我的发布参数没有将其发送给我的控制器?

控制器:

public ActionResult Admin(uint id, FormCollection collection) { 
    var username = collection.Get("username"); 
    var password = collection.Get("password"); 
    Helper.CreateUser(username,password); 
    return View("AdministerUsers"); 
} 

检视:

<% using (Html.BeginForm()){ %> 
    <fieldset> 
    <legend>Fields</legend> 
    <label for="username">username</label> 
    <%= Html.TextBox("username") %> 
    <label for="password">password:</label> 
    <%= Html.TextBox("password") %> 
    </fieldset> 
    <input type="submit" value="Add User" name="submitUser" /> 
<% } %> 

路由:

routes.MapRoute(
    "Admin", 
    "Admin/{id}", 
    new { controller = "Administration", action = "Admin"} 
); 
+0

您已指定。删除此行并重试一次 –

+0

@KundanSinghChouhan - 标签对表单值没有影响。 –

+1

改为使用'Get(“username”)',而不是使用'collection [“username”]''。它不应该有所作为,但我很好奇,如果它。虽然我会建议使用Tejs解决方案,而不是FormCollection,因为它更安全。 –

回答

0

的FormCollection不具有对应于用户名或密码属性; MVC绑定使用反射来查看对象以确定发布的数据绑定到的位置。

所以,你的情况,切换到该签名应该解决您的问题:

public ActionResult Admin(uint id, string username, string password) 
{ 
     // .. Do your stuff 
} 

由于参数包含“用户名”和“密码”,匹配您发布表单元素的名称,其中,它们包含的数据将被绑定到这些变量。

+0

FormCollection不需要具有与用户名或密码相对应的属性,它是与发布值对应的NameValue对的集合。 –

+0

是的,但据我所知,默认的模型联编程序不会将每个帖子值粘贴到字典/哈希表中,只是因为它在签名上,除非发布数据以特定方式格式化。 – Tejs

+0

是的,默认模型联编程序会将每个查询字符串或邮政值放入'FormsCollection'中。这就是要点,它相当于'Page.Request [“”]'' –

1

你能做到这一点的asp.net的MVC方式,并强烈键入您的视图模型

型号:

public class ViewModel 
    { 
     public string Username {get; set;} 
     public string Password {get; set;} 
    } 

强烈键入您的观点:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewModel>" %> //the ViewModel will need to have it's fully qualified name here 

然后使用MVC的默认模型绑定:

<% using (Html.BeginForm()){ %> 

    <%= Html.LabelFor(m => m.Username) %> 
    <%= Html.TextBoxFor(m => m.Username) %> 

    <%= Html.Label(m => m.Password) %> 
    <%= Html.TextBoxFor(m => m.Password) %> 

    <input type="submit" value="Add User" name="submitUser" /> 
<% } %> 

控制器:

[HttpPost] 
public ActionResult Admin(ViewModel model) 
{ 
    var username = model.Username; 
    var password = model.Password; 
    Helper.CreateUser(username,password); 
    return View("AdministerUsers"); 
} 
相关问题