繁体   English   中英

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

[英]ASP.NET MVC 3 Razor: Passing Data from View to Controller

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

您可以包装要在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" />

}

按下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”。 在该方法中,您可以接受模型或其他数据类型作为输入。 有关使用表单和razor mvc的示例,请参阅教程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM