Click here to Skip to main content
12,763,466 members (26,212 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

16K views
5 bookmarked
Posted 11 Jul 2012

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

You may also be interested in...

Comments and Discussions

 
AnswerIn tip/trick: MVC extension : SubmitButton Pin
licface131-Sep-14 23:48
memberlicface131-Sep-14 23: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170217.1 | Last Updated 12 Jul 2012
Article Copyright 2012 by StianSandberg
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid