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

MVC extension : SubmitButton

By , 12 Jul 2012
 

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)

About the Author

AlluvialDeposit
Software Developer (Senior)
Norway Norway
Member
Microsoft Certified Solutions Developer (MCSD)
 
My personal websites/projects:
CRM1.no - A free to use norwegian crm software
Fakturax - A free to use norwegian invoice software

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 12 Jul 2012
Article Copyright 2012 by AlluvialDeposit
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid