8

I'm a little bit confused with Html helpers in MVC3.

I used this syntax when creating my forms before:

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

this gives me

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

fine, that's what I needed then.

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

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

that would give me

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

but I still need to pass css class and id to this form and I can't find the way to do it simultaneously passing ReturnUrl parameter.

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

How do I do it?

Thanks.

2 Answers 2

11

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks pjumble, that is what I need. Didn't try to put ReturnUrl before FormMethod.Post. A little bit of magic is happening there, difficult to figure it out without someone's help.
3

1-Harder way: define routeValues 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 inline way: Use the Route value internally 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 note that in case you want to add post (FormMethod.Post) or get explicitly it comes after routeValues parameter

official source with good examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.