Simplify the extension of Asp.net MVC helper using routevaluedictionary

Source: Internet
Author: User
Tags actionlink

Asp.net MVC provides a large number of helper, such as the following helper:

 

Public   Static   String Actionlink ( This Htmlhelper, String Linktext, String Actionname, Object Routevalues, Object Htmlattributes)

 

In actual development, we cannot avoid extending helper, for example, extending a link method (MVC only provides actionlink and routelink, but does not extend the most common link)

 

Public   Static   String Link ( This Htmlhelper, String Linktext, String Linkhref, Object Htmlattributes)
{
.
}

 

There is an htmlattribute, which is the so-called "anonymous type" in C #3.0. It allows the user to write the following when calling this method:

 

<% = Html. Link ( " Caraq " , " Http://www.caraq.com " , New {@ Class = " Home " , Target = " _ Blank " }) %>

 

In the link method, how does one know the HTML attributes and values specified by the user?

After checking the MVC source code, we found that it uses a routevaluedictionary class defined in the system. Web. Routing component. Therefore, you can obtain the user-specified HTML attribute values as follows:

 

Public   Static   String Link ( This Htmlhelper, String Linktext, String Linkhref, Object Htmlattributes)
{
String Reval =   " <A href = \ " { 0 }\ " {1 }>{ 2 }</A> " ;
Stringbuilder =   New Stringbuilder ();
Foreach (VAR item In   New Routevaluedictionary (htmlattributes ))
{
Builder. append (item. Key +   " = \ "" + Item. Value + " \ "   " );
}
Return   String . Format (reval, linkhref, builder. tostring (), linktext );
}
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.