Kyl*_*e M 10 c# asp.net-mvc razor asp.net-mvc-3
我是.NET的全新东西.我有一个非常基本的网页与HTML表单.我希望'onsubmit'将表单数据从View发送到Controller.我已经看到类似的帖子,但没有一个涉及新的Razor语法的答案.如何处理'onsubmit',以及如何从Controller访问数据?谢谢!!
Ins*_*dBy 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" />
}
Run Code Online (Sandbox Code Playgroud)
按下Submit按钮时,Beginform内部的所有内容都将提交给"ControllerName"控制器的"ActionMethodName"方法.
在控制器端,您可以从视图中访问所有收到的数据,如下所示:
public ActionResult ActionMethodName(FormCollection collection)
{
string userName = collection.Get("username-input");
}
Run Code Online (Sandbox Code Playgroud)
上面的集合对象将包含我们从表单提交的所有输入条目.您可以按名称访问它们,就像访问任何数组一样: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
<input class="button" id="submit" type="submit" value="Submit" />
}
public ActionResult ActionMethodName(string id,string name)
{
string myId = id;
string myName = name;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将这两种方法结合使用,并将特定参数与Formcollection一起传递.由你决定.
希望能帮助到你.
编辑:当我写作时,其他用户也向您推荐了一些有用的链接.看一看.