2013-12-09 57 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可能會讓你開始。