Andre Borges
Andre Borges

Reputation: 1432

ASP.NET MVC - Usinig Html.For helpers with classes different form view model

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?

Upvotes: 0

Views: 428

Answers (2)

Shashank Sood
Shashank Sood

Reputation: 480

No need To look for any magic. You can directly add "shipping address" in your Product Model as well. What is the problem in adding that??

Upvotes: 0

SwedishProgrammer
SwedishProgrammer

Reputation: 111

There's a difference between your models and your view models. Models should reflect the database and your view models should be custom made to fit the view.

What you could do is creating a view model that contains all the properties you are interested in having contained in your view, and populate those fields with data from your database.

Perhaps it's not the neatest of solutions, but your view model could be as simple as:

public Order Order {get; set;}
public Product Product {get; set;}

And in the GET-method you get the order and product you want to display and and assign it to the view model.

Upvotes: 1

Related Questions