学习MVC有一段时间了。感叹于MVC的高扩展性。这里总结一些MVC常用扩展。就先从最常用的AjaxHelper&HTMLHelper开始记录。
一个最简单的例子。通过扩展方法扩展HTMLHelper
public static string Label(this HtmlHelper helper,string name,255); line-height:1.5!important">string value) { return string.Format("<label for='{0}'>{1}</label><br />",name,value); }
Html.Label(Anytao",tao")
再一个稍稍复杂的例子扩展AjaxHelper
Extensions
static MvcHtmlString TextBox(this AjaxHelper ajaxHelper,0); line-height:1.5!important"> name,AjaxOptions ajaxOptions,object htmlAttributes) { var tag = new TagBuilder(input); tag.MergeAttribute(nametypetext); tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); tag.MergeAttributes((ajaxOptions ?? new AjaxOptions()).ToUnobtrusiveHtmlAttributes()); return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); }
注意TagBuilder类和MergeAttribute方法。顾名思义用于构建HTML表情和属性
Controller
class AjaxHelperExtController : Controller
{
//
// GET: /AjaxHelperExt/
public ActionResult AjaxHelperExt()
{
View();
}
ActionResult GetTime()
{
return Content(Now Time:" + DateTime.Now.ToString());
}
}
<div id="divTime"></div> @Ajax.TextBox("search" AjaxOptions { Url = @Url.Action("GetTime"),UpdateTargetId = "divTime" InsertionMode.Replace },255); line-height:1.5!important">new { size = 50 })