问题描述:

After stepping through my code, I have verified that collection.Get("username"); is null in the below code, which means my post parameters just aren't making it into the controller. Can anyone spot the problem?

Controller:

public ActionResult Admin(uint id, FormCollection collection) {

var username = collection.Get("username");

var password = collection.Get("password");

Helper.CreateUser(username,password);

return View("AdministerUsers");

}

View:

<% 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" />

<% } %>

Routing:

routes.MapRoute(

"Admin",

"Admin/{id}",

new { controller = "Administration", action = "Admin"}

);

网友答案:

You could do it the asp.net mvc way and strongly type your view to a model

Model:

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

Strongly type your view:

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

Then use mvc's default model binding:

<% 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" />
<% } %>

Controller:

[HttpPost]
public ActionResult Admin(ViewModel model) 
{
    var username = model.Username;
    var password = model.Password;
    Helper.CreateUser(username,password);
    return View("AdministerUsers");
}
网友答案:

FormCollection doesn't have properties corresponding to Username or Password; MVC binding looks to the object using reflection to determine where posted data gets bound to.

So, in your case, switching to this signature should fix your problem:

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

Since the parameters contain 'username' and 'password', which match the names of the form elements you are posting, the data they contain will be bound to those variables.

相关阅读:
Top