I would like to use a helper for Submit button in MVC3. Is such a thing available? If not, then does anyone know where I could get some code for this. I would like one that allows me to pass a class attribute.
The HtmlHelper class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form.
HTML Helpers are methods that return a string. Helper class can create HTML controls programmatically. HTML Helpers are used in View to render HTML content. It is not mandatory to use HTML Helper classes for building an ASP.NET MVC application.
It goes through the every property in the model for displaying object. @Html. DisplayFor(modal => modal) :- This Display template helper is used with strongly typed views , if model has properties which return complex objects then this template helper is very useful.
Isn't it simple just to write
<input type="submit" class="myclassname"/>
In MVC, there are no such things like controls, that carry much application logic. In fact, it is possible but not recommended. What i want to say is that Html helpers are just making Html writing more comfortable and help you not write duplicate code. In your particular case, i think it is simpler to write direct html than that with helper. But anyways, if you want to, it is contained in MVC Futures Library. Method is called SubmitButton
Just add to your project class with such code:
using System.Text;
namespace System.Web.Mvc
{
public static class CustomHtmlHelper
{
public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText, object htmlAttributes = null)
{
StringBuilder html = new StringBuilder();
html.AppendFormat("<input type = 'submit' value = '{0}' ", buttonText);
//{ class = btn btn-default, id = create-button }
var attributes = helper.AttributeEncode(htmlAttributes);
if (!string.IsNullOrEmpty(attributes))
{
attributes = attributes.Trim('{', '}');
var attrValuePairs = attributes.Split(',');
foreach (var attrValuePair in attrValuePairs)
{
var equalIndex = attrValuePair.IndexOf('=');
var attrValue = attrValuePair.Split('=');
html.AppendFormat("{0}='{1}' ", attrValuePair.Substring(0, equalIndex).Trim(), attrValuePair.Substring(equalIndex + 1).Trim());
}
}
html.Append("/>");
return new MvcHtmlString(html.ToString());
}
}
}
And usage example:
@Html.SubmitButton("Save", new { @class= "btn btn-default", id="create-button" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With