2

I have the following:

 @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))

I tried this:

 @using (Html.BeginForm(new { @class = "form", ReturnUrl = ViewBag.ReturnUrl }))

However I don't see the class "form" added. Is there something wrong with the way I am defining it ?

0

2 Answers 2

4

Try defining htmlAttributes parameter explicitly like so:

@using (Html.BeginForm(null, null, FormMethod.Post, htmlAttributes: new { @class = "form-class" })) {
}

Update after reading comment Try using one of the BeginForm overloads that allow you to specify route objects (I have not tested this because I dont have an IDE nearby)

@using (Html.BeginForm("Action", "Controller", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, htmlAttributes: new { @class = "form-class" })) {
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much. How would I include ReturnUrl = ViewBag.ReturnUrl ?
2

It's a pain if you want to use the default form, but just add some attributes. Here is the overloaded method signature that accepts attributes. Therefore, you'll need to also supply the action name, controller name, and form method. The first form you have is setting the RouteValueCollection.

What I've done in the past is create my own helper that circumvents the limitation. Here is an example extension method to short circuit all the other parameters.

using System.Web.Mvc.Html;

namespace MySite.Extensions {
    public static class HtmlFormExtensions {
        public static MvcForm BeginForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues, IDictionary<string, Object> htmlAttributes) {
            return htmlHelper.BeginForm(null, null, routeValues, FormMethod.Post, htmlAttributes);
        }
    }
}

Be sure to include your namespace in the view (or all views via web.config), then call it like so:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }, new { @class = "form" }))

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.