Asp. Net MVC's custom Extension Method for class HtmlHelper and how to call

Source: Internet
Author: User

C # There have been a lot of articles about the extension method since the extension method has been released for a long time. I will not introduce it here. If you do not understand it, you can refer to Baidu or google. There are also a lot of explanations in the garden.

You can see that this is the three overload methods for TextBoxFor in Microsoft MVC. We can also customize the extension for TextBoxFor (as long as we can implement the style we want), so it is much easier to call.

Now, implement one by yourself.

        public static MvcHtmlString TextBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, DateTime>> expression)        {            return htmlHelper.TextBoxFor(expression, new { @class = "date" });        }

Then we can see that this strong text will be selectively bound to date fields when it is bound to the Model. It does not conflict with the built-in system, because although the method names are the same, but the parameter types are not the same, you can pay attention when you expand it yourself.
Let's call it.

We can see that the three reloads have now become four, and this is exactly our custom extension.

Of course we should reference it before calling it. Here we provide three methods for reference:

First, you can reference the page in the corresponding View to @ using namespace.

Type 2: You can configure it in web. config, so you do not need to reference it in the view.

<Configuration> <system. web> <pages> <namespaces> <add namespace = "namespace name"/> </namespaces> </pages> </system. web> </configuration>

Third: Let's take a look at the namespace System where the built-in methods are located. web. mvc. html, and then change the namespace of our custom extension method to this, so that no configuration or reference is required.
Of course there may be other methods.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.