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