2012-09-27 101 views
0

我開始使用mvc並設計一個簡單的登錄程序。 我有兩個輸入用戶名和密碼登錄屏幕查看。 但顯然無法得到我如何將我的視圖的輸入值傳遞給我使用剃鬚刀的控制器 。這裏是我的片段。MVC查看控制器通過

<table> 
    <tr> 
     <td> 
      UserName: 
     </td> 
     <td> 
      @Html.TextBox("userName") 
     </td> 
    </tr> 
     <tr> 
     <td> 
      Password 
     </td> 
     <td> 
      @Html.Password("Password") 
     </td> 
    </tr> 
    <tr> 
     <td colspan="2"> 
      @Html.ActionLink("login", "SignIn") 
     </td> 
    </tr> 
</table> 

和我的控制器看起來像這樣(我能夠使用重定向操作鏈接只是紫霞大約將值傳遞給控制器​​。)

public ActionResult SignIn() 
{ 
    //string userName = Request["userName"]; 
    return View("Home"); 
} 

回答

2

您可以在表單提交方法中聲明表單提交方法的表單提交方法中包含上面的HTML內容,內容爲POST

@using (Html.BeginForm("SignIn", "Controller", FormMethod.Post, new { id = "form1" })) 
{ 
    <table> 
    <tr> 
     <td> 
      UserName: 
     </td> 
     <td> 
      @Html.TextBox("userName") 
     </td> 
    </tr> 
     <tr> 
     <td> 
      Password 
     </td> 
     <td> 
      @Html.Password("Password") 
     </td> 
    </tr> 
    <tr> 
     <td colspan="2"> 
      <input type="submit" value="login" name="login" /> 
     </td> 
    </tr> 
</table> 
} 

然後,你可以把Post行動在你的控制器:

[HttpPost] 
public ActionResult SignIn(FormCollection frmc) 
{ 
    /// Extracting the value from FormCollection 
    string name = frmc["userName"]; 
    string pwd = frmc["Password"]; 
    return View("Home"); 
} 
+0

完美!這讓我質疑。那是最佳做法?還是有更好的? –

+0

就我個人而言,我曾經這麼做過簡單的表單提交活動..... –

+2

我會用'@model VmLoginParams'來製作視圖,並讓控制器的後續操作採用'public ActionResult SignIn(VmLoginParams params)'在Html代碼,然後你可以做'@ Html.EditorFor(m => m.UserName)@ Html.ValidationMessageFor(m => m.UserName)'並在控制器中檢查ModelState.IsValid:if(!ModelState.IsValid)返回查看(params)'(另請參閱:http://www.mikesdotnetting.com/Article/188/View-Model-Design-And-Use-In-Razor-Views) –

0

總結你的表形式:

@using (Html.BeginForm("SignIn", "controllerName", FormMethod.POST)) 
{ 
<table> 
... 
</table> 
<input type="submit" value="Sign in" /> 
} 

並在控制器寫:

[HttpPost] 
public ActionResult SignIn(string userName, string Password) 
{ 
//sign in and redirect to home page 
} 
0

查看:

@using (Html.BeginForm("SignIn", "Controller", FormMethod.Post, new { id = "form1" })) 
{ 
<table> 
<tr> 
    <td> 
     UserName: 
    </td> 
    <td> 
     @Html.TextBox("userName") 
    </td> 
</tr> 
    <tr> 
    <td> 
     Password 
    </td> 
    <td> 
     @Html.Password("Password") 
    </td> 
</tr> 
<tr> 
    <td colspan="2"> 
     <input type="submit" value="login" name="login" /> 
    </td> 
</tr> 
</table> 
} 

型號:

public string userName{get;set;} 
public string Password{get;set;} 

控制器:

[HttpPost] 
public ActionResult SignIn(Model obj) 
{ 
    //sign in and redirect to home page 
    string userName = obj.username; 
    string password = obj.password; 
} 

這可能對您有幫助。