ASP.NET MVC 3 Razor:将数据从视图传递到控制器

我是.NET的全新东西。 我有一个带有HTML表单的非常基本的网页。 我希望’onsubmit’将表单数据从View发送到Controller。 我已经看过类似的post,但没有一个涉及新的Razor语法的答案。 如何处理’onsubmit’,以及如何从Controller访问数据? 谢谢!!

您可以将要传递的视图控件包装在Html.Beginform中。

例如:

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

当按下Submit按钮时,该Beginform内部的所有内容都将提交给“ControllerName”控制器的“ActionMethodName”方法。

在控制器端,您可以从视图中访问所有收到的数据,如下所示:

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

上面的集合对象将包含我们从表单提交的所有输入条目。 您可以按名称访问它们,就像访问任何数组一样:collection [“blah”]或collection.Get(“blah”)

您还可以直接将参数传递给控制器​​,而无需使用FormCollection发送整个页面:

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

或者,您可以将这两种方法结合使用,并将特定参数与Formcollection一起传递。 由你决定。

希望能帮助到你。

编辑:当我写作时,其他用户也向您推荐了一些有用的链接。 看一看。

按以下方式定义表单:

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

将调用控制器“ControllerName”中的方法“ControllerMethod”。 在该方法中,您可以接受模型或其他数据类型作为输入。 有关使用表单和razor mvc的示例,请参阅本教程。