2013-12-09 56 views
0

我有UserSample模型与两个属性(用户名,密码)的视图,我想要实现的是从文本框中获取这些值,并将它们存储到对象模型,然后在Action方法中使用此对象并对其进行操作。对象模型属性未提交后提交表格

但是,在此代码中,在填充文本框字段提交表单后,操作方法索引中的对象属性始终为空。

控制器:

public ActionResult Index(UserSample user) //this is the object which properties I want to be asigned. 
     { 
      if (user != null) 
      { 

      } 

      return View(); 
     } 

查看:

@using (@Html.BeginForm("Index","Login")) 
{ 
    <table> 
     <tr> 
      <td>Username: </td> 
      <td>@Html.TextBox("Username")</td> 
     </tr> 
     <tr> 
      <td>Password: </td> 
      <td>@Html.TextBox("Password")</td> 
     </tr> 
     <tr> 
      <td></td> 
      <td><input id="btnSubmit" type="submit" value="Submit" /></td> 
     </tr> 
    </table> 
} 

回答

2

尝试加入这一行到您的视图:

@model UserSample 

您可能需要包括命名空间存在。例如,MyApp.Models.UserSample

那么你可以使用stronly类型HTML-助手:

<td>@Html.TextBoxFor(model => model.UserName)</td> 

<td>@Html.TextBoxFor(model => model.Password)</td> 

你应该装点Index(UserSample user)方法与HttpPost属性:

public ActionResult Index() 
{ 
    // Get method. 
    UserSample model = new UserSample(); 
    return View(model); 
} 

[HttpPost] 
public ActionResult Index(UserSample user) 
{ 
    // POST method. 
} 

当你交现在的形式,UserSample对象应该填入表单中的值。

如果你不明白模型绑定,我建议你看看它。 This tutorial可能会让你开始。