How to pass request parameter and class attribute in Html.BeginForm in MVC3?

I am a bit confused with the Html helpers in MVC3.

I used this syntax when creating my forms before:

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

it gives me

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

excellent, then what I need then.

Now I need to pass the ReturnUrl parameter to the form, so I can do it like this:

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

which would give me

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

but I still need to pass the css class and id to this form, and I cannot find a way to do this while passing the ReturnUrl parameter.

If I add FormMethod.Post , it will add all my parameters as attributes to the form tag, without FormMethod.Post it will add them as query string parameters.

How can I do it?

Thanks.

+6
source share
2 answers

You can use:

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

this will give:

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

1-Difficult way: define routeValues ​​parameters externally and then use the variable

 @{ 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- simpler built-in way: use the route value inside with Razor

 @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"> 

Just remember that if you want to add a message (FormMethod.Post) or explicitly receive it after the routeValues ​​parameter

official source with good examples

+1
source

Source: https://habr.com/ru/post/912310/


All Articles