Navigation and service panel


Content

Add custom attributes to form tag with Sitecore MVC

By Kevin Brechb├╝hl on 18. August 2014, No comments

A form tag often needs additional attributes like the css class. Because in Siteore MVC we can have multiple renderings and controllers on one page request, this can't be done exactly the same way as in pure ASP.NET MVC. In this small blog post I will explain you why and how you can do this with Sitecore MVC.

When you wan't to create a form in Razor, this is very simple:

@using (Html.BeginForm())
{
    ...
}

And results in the following html markup:

<form action="/mysite/mypage" method="post">
    ...
</form>

This is same in pure ASP.NET MVC and Sitecore MVC. The method BeginForm() takes the current raw url as action to post to. To add additional attributes we need to specify a collection of these attributes, but there is no extension method to only specify the attributes: we also need to add the controller and the action we want to post to (for example to add a css class and a custom attribute):

@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { @class = "css_class", myattribute = "myvalue" }))
{
    ...
}

This work for ASP.NET MVC, but results in the following action with Sitecore MVC:

<form action="/api/sitecore/MyController/MyAction" class="css_class" method="post" myattribute="myvalue">
    ...
</form>

This is because /api/sitecore/{controller}/{action} is the route taken to generate the action url. There are several ways of how to post forms with Sitecore MVC (see a summary from Martina Welander and another perspective from me). In our case we wan't to post to the current raw url, as in the first example here. This can be achieved when we specify the action url as an attribute and passing null for the controller/action. Like here:

@using (Html.BeginForm(null, null, FormMethod.Post, new { @action = this.Request.RawUrl, @class = "css_class", myattribute = "myvalue" }))
{
    ...
}

Which results in exactly the form tag we want:

<form action="/mysite/mypage" class="flex_formcontainer" method="post" myattribute="myvalue">
    ...
</form>

If you have more forms in your solution, it's maybe worth to create en extension method on System.Web.Mvc.HtmlHelper.

Categories  ASP.NET MVC  Best Practice Tags  Attributes  Forms  Html

No comments

Add your comment

Your email address will not be published. Required fields are marked *

*