Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC extension : SubmitButton

0.00/5 (No votes)
12 Jul 2012 1  
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));
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here