2012-04-03 60 views
6

我对MVC3中的Html帮助器有些困惑。如何将查询参数和类属性传递给MVC3中的Html.BeginForm?

我之前我创建表单时使用此语法:

@using (Html.BeginForm("action", "controller", FormMethod.Post, new { @class = "auth-form" })) { ... } 

这给了我

<form action="/controller/action" class="auth-form" method="post">...</form> 

细,这就是我需要的东西,然后。

现在我需要RETURNURL参数传递到表单,所以我可以做这样的:

@using (Html.BeginForm("action", "controller", new { ReturnUrl="myurl" })) { ... } 

,会给我

<form action="/controller/action?ReturnUrl=myurl" method="post"></form> 

,但我仍然需要通过css类和编号为这种形式,我无法找到同时传递ReturnUrl参数的方式。

如果我添加FormMethod.Post它将所有我的参数作为属性添加到窗体标记,而不添加FormMethod.Post它将它们添加为查询字符串参数。

我该怎么做?

谢谢。

回答

10

您可以使用:

@using (Html.BeginForm("action", "controller", new { ReturnUrl="myurl" }, FormMethod.Post, new { @class = "auth-form" })) { ... } 

这将给:

<form action="/controller/action?ReturnUrl=myurl" class="auth-form" method="post"> 
    ... 
</form> 
+1

感谢pjumble,这就是我所需要的。没有尝试在FormMethod.Post之前放置ReturnUrl。在那里发生了一点魔法,如果没有人的帮助,很难弄清楚。 – Burjua 2012-04-03 16:11:18

1

1 - 哈德方式:外部定义routeValues然后使用可变

@{ 
    var routeValues = new RouteValueDictionary(); 
    routeValues.Add("UserId", "5"); 
    // you can read the current QueryString from URL with equest.QueryString["userId"] 
} 
@using (Html.BeginForm("Login", "Account", routeValues)) 
{ 
    @Html.TextBox("Name"); 
    @Html.Password("Password"); 
    <input type="submit" value="Sign In"> 
} 
// Produces the following form element 
// <form action="/Account/Login?UserId=5" action="post"> 

2 - 简单的直列方法:使用剃刀内部的路线值

@using (Html.BeginForm("Login", "Account", new { UserId = "5" }, FormMethod.Post, new { Id = "Form1" })) 
{ 
    @Html.TextBox("Name"); 
    @Html.Password("Password"); 
    <input type="submit" value="Sign In"> 
} 
// Produces the following form element 
// <form Id="Form1" action="/Account/Login?UserId=5" action="post"> 

只是注意,如果你想添加后(FormMethod.Post)或得到明确谈到后routeValues参数

official source with good examples