What is the best way to extend Html Helper TextboxFor? Is there a way to reuse the defautl implementation?
Creating HTML Helpers with Extension Methods If you want to create HTML Helpers that work just like the standard HTML Helpers included in the ASP.NET MVC framework then you need to create extension methods. Extension methods enable you to add new methods to an existing class.
HTML Helpers are managed within View to execute HTML content. We can use HTML Helpers to implement a method that returns a string. This tutorial discusses how you can define or create custom HTML Helpers that you can use within your MVC views.
There are two ways in MVC to create custom Html helpers as below. We can create our own HTML helper by writing extension method for HTML helper class. These helpers are available to Helper property of class and you can use then just like inbuilt helpers. Add new class in MVC application and give it meaningful name.
Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.
You can create your extension methods (in a static class), for example:
public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
// call original method
MvcHtmlString result = InputExtensions.TextBoxFor(helper, expression);
// do modification to result
return result;
}
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