Click here to Skip to main content
Click here to Skip to main content

Tagged as

MVC extension : SubmitButton

, 12 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

StianSandberg
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
Follow on   Twitter   LinkedIn

Comments and Discussions

 
AnswerIn tip/trick: MVC extension : SubmitButton Pinmemberlicface131-Sep-14 23:48 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150414.1 | Last Updated 12 Jul 2012
Article Copyright 2012 by StianSandberg
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid