MVC extension : SubmitButton





5.00/5 (4 votes)
Extension to create a submit button the clean way
Introduction
I really like to work with razor views. It's clean and easy. But when I create forms, I don't like that I have to use HTML to create the submit-button. So I created an extension to create the submit button for me.
Using the Code
Regular forms with razor:
@Html.TextBoxFor(m=>m.Name)
@Html.TextBoxFor(m=>m.Email)
<input type="submit" value="Click me" name="buttonName" class="actionButton"/>
Using this extension creates a cleaner form (in my opinion):
@Html.TextBoxFor(m=>m.Name)
@Html.TextBoxFor(m=>m.Email)
@Html.SubmitButton("buttonName", "Click me", new { @class = "actionButton" })
The Extension Method
public static MvcHtmlString SubmitButton
(this HtmlHelper helper, string name, string text, object htmlAttributes = null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var builder = new TagBuilder("input");
if (htmlAttributes != null)
builder.MergeAttributes(attributes);
builder.Attributes.Add("type", "submit");
builder.Attributes.Add("value", text);
builder.Attributes.Add("name", name);
builder.Attributes.Add("id", name);
builder.AddCssClass("submit");
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}