Click here to Skip to main content
15,893,622 members
Articles / Programming Languages / C#
Tip/Trick

MVC extension : SubmitButton

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
12 Jul 2012CPOL 26.9K   5   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
@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
@Html.TextBoxFor(m=>m.Name)
@Html.TextBoxFor(m=>m.Email)
@Html.SubmitButton("buttonName", "Click me", new { @class = "actionButton" })  

The Extension Method

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Aurum AS
Norway Norway
Microsoft Certified Solutions Developer (MCSD)

Personal website:
stian.net

My projects:
CRM1.no - A free to use norwegian crm software
Fakturax - A free to use norwegian invoice software
Timeføring.no - A free to use norwegian timereg software
MittUtlegg - A free to use norwegian software for receipts
SupportWeb - A free to use norwegian software customersupport

Comments and Discussions

 
AnswerIn tip/trick: MVC extension : SubmitButton Pin
licface131-Sep-14 22:48
licface131-Sep-14 22:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.