2012-06-08 223 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的示例。

相关问题