如果Get Action返回带有“Car”模型的View.视图显示来自对象的信息,并将输入发送到表单内的另一个操作,该操作采用“付款”类型的对象
视图上的模型是Car类型,并为我提供了强大的html支持和一些其他功能,如displaytext.但是对于发布我没有像TextBox那样的Htmlhelper支持(x => x.amount我需要使它像@ Html.TextBox(“Amount”……)
它可能,但这是唯一的选择吗?
解决方法
你可以这样做:
@{ var paymentHtml = Html.HtmlHelperFor<Payment>(); } @paymentHtml.EditorFor(p => p.Amount)
使用此扩展方法:
public static class HtmlHelperFactoryExtensions { public static HtmlHelper<TModel> HtmlHelperFor<TModel>(this HtmlHelper htmlHelper) { return HtmlHelperFor(htmlHelper,default(TModel)); } public static HtmlHelper<TModel> HtmlHelperFor<TModel>(this HtmlHelper htmlHelper,TModel model) { return HtmlHelperFor(htmlHelper,model,null); } public static HtmlHelper<TModel> HtmlHelperFor<TModel>(this HtmlHelper htmlHelper,TModel model,string htmlFieldPrefix) { var viewDataContainer = CreateViewDataContainer(htmlHelper.ViewData,model); TemplateInfo templateInfo = viewDataContainer.ViewData.TemplateInfo; if (!String.IsNullOrEmpty(htmlFieldPrefix)) templateInfo.HtmlFieldPrefix = templateInfo.GetFullHtmlFieldName(htmlFieldPrefix); ViewContext viewContext = htmlHelper.ViewContext; ViewContext newViewContext = new ViewContext(viewContext.Controller.ControllerContext,viewContext.View,viewDataContainer.ViewData,viewContext.TempData,viewContext.Writer); return new HtmlHelper<TModel>(newViewContext,viewDataContainer,htmlHelper.RouteCollection); } static IViewDataContainer CreateViewDataContainer(ViewDataDictionary viewData,object model) { var newViewData = new ViewDataDictionary(viewData) { Model = model }; newViewData.TemplateInfo = new TemplateInfo { HtmlFieldPrefix = newViewData.TemplateInfo.HtmlFieldPrefix }; return new ViewDataContainer { ViewData = newViewData }; } class ViewDataContainer : IViewDataContainer { public ViewDataDictionary ViewData { get; set; } } }