2012-06-08 221 views
10

我是全新.NET產品。我有一個HTML表單非常基本的網頁。我希望'onsubmit'將表單數據從視圖發送到控制器。我已經看到類似的帖子,但沒有任何答案涉及到新的ish Razor語法。我如何處理'onsubmit',以及如何從Controller訪問數據?謝謝!!ASP.NET MVC 3 Razor:將數據從視圖傳遞到控制器

回答

26

你可以用Html.Beginform來包裝你想要傳遞的視圖控件。

例如:

@using (Html.BeginForm("ActionMethodName","ControllerName")) 
{ 
... your input, labels, textboxes and other html controls go here 

<input class="button" id="submit" type="submit" value="Submit" /> 

} 

當提交按鈕被按下的那Beginform內一切都將提交給「ControllerName」控制你的「ActionMethodName」的方法。

控制器端,你可以從這樣的觀點訪問所有接收到的數據:

public ActionResult ActionMethodName(FormCollection collection) 
{ 
string userName = collection.Get("username-input"); 

} 

上面收集的對象將包含我們從表單提交的所有您輸入的條目。您可以按名稱訪問它們,就像你訪問任何數組: 收集[「嗒嗒」] 或collection.Get(「嗒嗒」)的情況下直接與發送整個頁面

您也可以傳遞參數給你的控制器FormCollection:

@using (Html.BeginForm("ActionMethodName","ControllerName",new {id = param1, name = param2})) 
{ 
... your input, labels, textboxes and other html controls go here 

<input class="button" id="submit" type="submit" value="Submit" /> 

} 

public ActionResult ActionMethodName(string id,string name) 
{ 
string myId = id; 
string myName = name; 

} 

或者你可以結合使用這兩種方法,並將特定參數和Formcollection一起傳遞。隨你便。

希望它有幫助。

編輯:當我在寫其他用戶時也提到了一些有用的鏈接。看一看。

+0

太好了,非常感謝! –

+0

對於組合你也可以這樣做:HttpContext.Request.Form [「index」];通過這種方式,您不必在參數中添加FormCollection。 –

0

以下列方式定義形式:

@using (Html.BeginForm("ControllerMethod", "ControllerName", FormMethod.Post))

將在控制器「ControllerName」方法「ControllerMethod」的呼叫。 在該方法中,您可以接受模型或其他數據類型作爲輸入。請參閱this教程,瞭解使用表單和剃鬚刀mvc的示例。

相關問題