2012-04-03 15 views
6

MVC3のHtmlヘルパーとちょっと混乱しています。私のフォームを作成するときに、私は前にこの構文を使用しMVC3のHtml.BeginFormにクエリパラメータとクラス属性を渡す方法は?

:これは私の

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

罰金を与える

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

、それは私がその後、必要なものです。

は今、私は、フォームににreturnurlパラメータを渡す必要があるので、私はこのようにそれを行うことができます。

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

は、それは私に

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

を与えるだろうが、私はまだCSSクラスを渡す必要があると私はこのフォームにIDと私はそれを同時に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 routeValuesパラメータの後に来る明示的に取得したいことに注意してください。 'FormMethod.Post'の前にReturnUrlを置こうとしませんでした。ちょっとした魔法がそこで起きている。誰かの助けなしにそれを理解することは難しい。 – Burjua

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 - シンプルなインラインを使用しますway:RazorでRouteの値を内部的に使用する

@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)のポストを追加したり、それはそれは私が必要なもので、

official source with good examples

関連する問題