tags:

views:

50

answers:

3

What is the better way to Get And Post different models with only one view.

e.g I have a set of controls each control have its own model. I want to load them in one view according with conditions. And then on post i want to retrieve the values from this view.

What is the better practice for that?

A: 

Create a composite View Model that exposes each individual model as a property.

Daz Lewis
Very Interesting. Any examples?
Juk
yes see my example (I called it artificial but composite might be a better name)
jao
@Jao I got it.Only one model where properties represented all my partial models which i want to display on that view.Thanks!
Juk
A: 

Hey, if I understand your question correctly, here is what I would do:

Create partial views for the different models that you need in order to be able to call them from the "main" view. Then, pass the models in the ViewData and whenever you need to render a partial do the following:

<%Html.RenderPartial("PartialViewName", ViewData["Model"]);%>
sTodorov
Yes i am doing like this already. But then to get the data from any of this partial i have to have associated action which accepted only particular model(model witch associated with current partial on the view). In such case if i have N partials i have to create N HttpPost actions. Looks like a bit bulky way of doing this.
Juk
That is true, but, in my opinion, you will preserve separation of your models. So every model is associated with its action result. You can reuse the models and the action results. In the case of the composite model you would still need to do that to preserve the separation, however you will introduce one artificial object
sTodorov
+1  A: 

I create a artificial model like this:

public class CustomerViewData {
    public Customer customer { get; set; }
    public Ticket ticket { get; set; }
    public Decimal price { get; set; }
}

In your controller you call CustomerViewData and fill it with the data you need in your view:

CustomerViewData.Customer = _customerRepository.GetCustomerById(1);

Then you pass the CustomerViewData to your view. In your View you add

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.CustomerViewData>" %>

Now you can call <%= Model.Customer.Name %> to display the customer's name (given that your Customer object has a Name property).

(the above is just an example, actual contents may of course be much more logical).

jao