In my controller I have 2 simple methods for viewing and ordering products
[HttpGet]
public ActionResult Product(int id)
{
Product product = Repository.GetProduct(id);
return View(product);
}
[HttpPost]
public ActionResult Order(Order order)
{
var orderResult = OrderProcessor.Process(order);
return orderResult.Success ? View("OrderSuccess") : View("OrderFail");
}
The Order class contains fields from the view that customers must fill:
public class Order
{
public int ProductId { get; set; }
[Range(1, 10, ErrorMessage = "Quantity must be a number from 1 to 10")]
public int Quantity { get; set; }
[Required(ErrorMessage = "Address not specified")]
public string ShippingAddress { get; set; }
// other order info
}
In my view I want to use HTML helpers for form fields like @Html.TextBoxFor(x => x.ShippingAddress)
to enable Javascript client validation. But the problem is that MVC only allows these helpers to be used for properties of the view model (in my case the Product
class) and my view model doesn't contain ShippingAddress
.
To get these helpers working I need to have the same class for the model of the Product
view and the parameter of the Order
method. But this doesn't make any sense in my case. The view model shold contain product properties (name, price, description, etc.) while the POST method parameter should contain user input (quantity, address, etc).
I would like to be able to use HTML helpers with the properties of the Order
class like this:
@Html.TextBoxFor<Order>(x => x.ShippingAddress)
Is there a way to achieve this (maybe via an extension to MVC)? Or is there some other workaround for this problem?