asp.net-mvc - 强类型 html 助手,具有不同的 get 和 post 模型

标签 asp.net-mvc

如果获取操作返回具有“汽车”模型的 View 。该 View 显示来自对象的信息,并获取输入以在表单中发布到另一个采用“Payment”类型的对象的操作

View 上的模型属于 Car 类型,并为我提供了强类型 html 支持和一些其他功能,例如显示文本。但是对于发布,我没有像 TextBox(x => x.amount 一样的 Htmlhelper 支持,我需要将其设置为 @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; }
   }
}

关于asp.net-mvc - 强类型 html 助手,具有不同的 get 和 post 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354019/

相关文章:

asp.net-mvc - 在哪里/如何将 Solr 安装到 ASP.net MVC 应用程序中(使用 nHibernate/存储库模式)

asp.net-mvc - 如何将多选列表选定的项目传递回 Controller ?

c# - 在 ASP.NET 中并行执行 .NET HttpWebRequests 的建议

asp.net-mvc - 带有 Bootstrap 3 的 ASP.NET MVC 未正确呈现

asp.net - <access sslFlags ="Ssl.SslRequireCer"> 在 .net 核心

asp.net-mvc - 将数据对象临时保存在 MVC Controller 、MVC、MVC Controller 临时存储中

javascript - @Html.TextBoxFor 文本改变事件

asp.net-mvc - 与 ASP.NET WebForms 相比,ASP.NET MVC 页面的 'page lifecycle' 是什么?

c# - 向 EditorFor 添加一个类 - razor c#

ASP.NET MVC - 在哪里放置数据库查询