1. Define a required method, the returned type is mvchtmlstring
/// <summary> ///Generate category Dropdown-list box, select the specified item/// </summary> /// <param name= "html" ></param> /// <param name= "SelectedValue" ></param> /// <returns></returns> Public StaticMvchtmlstring Selectlist_category ( ThisHtmlHelper HTML,LongSelectedValue) {data.irepository _irepository=Newdata.datarepository (); StringBuilder SB=NewStringBuilder (); Sb. Append ("<select name= ' category ' id= ' category ' >"); foreach(varIinch_irepository.getmodel<category>()) { if(i.id = = SelectedValue && SelectedValue! =0) sb. AppendFormat ("<option value= ' {0} ' selected= ' selected ' >{1}</option>", I.id, i.name); Elsesb. AppendFormat ("<option value= ' {0} ' >{1}</option>", I.id, i.name); } sb. Append ("</select>"); returnmvchtmlstring.create (sb.) ToString ()); } /// <summary> ///Generate category drop-down list box/// </summary> /// <param name= "html" ></param> /// <returns></returns> Public StaticMvchtmlstring Selectlist_category ( Thishtmlhelper HTML) { returnSelectlist_category (HTML,0); }
@Html. Selectlist_category ()
As we can see from the code, this extension is actually an extension of the HtmlHelper object on the ViewPage page class, whose object name is HTML, so in the page that inherits the ViewPage or Viewusercontrol, can use the Selectlist_category extension method
Original: http://www.cnblogs.com/lori/archive/2012/03/05/2381196.html
MVC: Using mvchtmlstring to generate HTML in the background