我对 .NET 相关技术完全不熟悉。我有一个非常基本的包含 HTML 表单的网页。我希望在“onsubmit”时将表单数据从视图发送到控制器。我看到了类似的帖子,但没有涉及新的 Razor 语法的答案。我该如何处理“onsubmit”,以及如何从控制器访问数据?谢谢!
我对 .NET 相关技术完全不熟悉。我有一个非常基本的包含 HTML 表单的网页。我希望在“onsubmit”时将表单数据从视图发送到控制器。我看到了类似的帖子,但没有涉及新的 Razor 语法的答案。我该如何处理“onsubmit”,以及如何从控制器访问数据?谢谢!
@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["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;
}
你也可以同时使用这两种方法,并且在Formcollection中传递特定的参数。完全由你决定。
希望对你有所帮助。
编辑:当我写作时,其他用户也向你提供了一些有用的链接。可以看一下。
以下是定义表单的方式:
@using (Html.BeginForm("ControllerMethod", "ControllerName", FormMethod.Post))
将调用控制器“ControllerName”中的方法“ControllerMethod”。 在该方法中,您可以接受模型或其他数据类型作为输入。请参阅this教程,了解使用表单和Razor MVC的示例。