What is the better way to Get And Post different models with only one view.
e.g I have a set of controls each 开发者_StackOverflow中文版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?
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).
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"]);%>
Create a composite View Model that exposes each individual model as a property.
精彩评论