I have found a solution which involves creating a new html helper. The OP is correct in saying that it is sometimes inappropriate to use the same class as a parameter for the action method as well as the viewpage. Sometimes we want to pass MORE information to the ViewPage than what the user gives back to us in the form post.
The solution I came up with is to use a HtmlHelper extension method, which I called HtmlHelperFor(T obj) which I use as below:
<% var productForm = Html.HtmlHelperFor(Model.Product); %>
and then I use it as below:
<%= productForm.TextBoxFor(x => x.Name) %>
The extension method is below:
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);
}
The ViewDataContainer is an implementation of the IViewDataContainer interface found in Sysetm.Web.Mvc:
public class ViewDataContainer : System.Web.Mvc.IViewDataContainer
{
public ViewDataContainer(System.Web.Mvc.ViewDataDictionary viewData)
{
ViewData = viewData;
}
public System.Web.Mvc.ViewDataDictionary ViewData { get; set; }
}
the above calls will allow you to have a Product
object as part of the parameters of the method that accepts the POST, instead of a class which contains project which you would normally pass to your view.