我找到了一个涉及创建新 html 帮助程序的解决方案。 OP 正确地说,有时将同一类用作操作方法和视图页面的参数是不合适的。有时我们希望向 ViewPage 传递的信息比用户在表单帖子中返回给我们的信息更多。
我想出的解决方案是使用 HtmlHelper 扩展方法,我称之为 HtmlHelperFor(T obj),如下所示:
<% var productForm = Html.HtmlHelperFor(Model.Product); %>
然后我如下使用它:
<%= productForm.TextBoxFor(x => x.Name) %>
扩展方法如下:
public static HtmlHelper<T> HtmlHelperFor<T>(this HtmlHelper html, T model)
{
var newViewData = new ViewDataDictionary(html.ViewDataContainer.ViewData) { Model = model };
ViewContext newViewContext = new ViewContext(html.ViewContext.Controller.ControllerContext, html.ViewContext.View, newViewData, html.ViewContext.TempData, html.ViewContext.Writer);
var viewDataContainer = new ViewDataContainer(newViewContext.ViewData);
return new HtmlHelper<T>(newViewContext, viewDataContainer, html.RouteCollection);
}
ViewDataContainer 是 Sysetm.Web.Mvc 中的 IViewDataContainer 接口的实现:
public class ViewDataContainer : System.Web.Mvc.IViewDataContainer
{
public ViewDataContainer(System.Web.Mvc.ViewDataDictionary viewData)
{
ViewData = viewData;
}
public System.Web.Mvc.ViewDataDictionary ViewData { get; set; }
}
上述调用将允许您将 Product 对象作为接受 POST 的方法的参数的一部分,而不是包含通常传递给视图的项目的类。