问题
For example, I have 3 models with an Id (int), a Name (string) and an active (bool). It's possible to use just one view for these models with the same properties ? A technique like a generic object ? Inheritance ? It's to avoid to write multiple views with the same HTML code.
回答1:
You could create a ViewModel.
For sample:
public class CustomerViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
And create another ViewModel with a type like this:
public class CustomersViewModel
{
public CustomerViewModel Customer1 { get; set; }
public CustomerViewModel Customer2 { get; set; }
public CustomerViewModel Customer3 { get; set; }
}
and type your view with this type:
@model CustomersViewModel
Or just use an collection to type your view
@model List<CustomerViewModel>
Take a look at this anwser! https://stackoverflow.com/a/694179/316799
回答2:
In a view you can either
- specify shared base class for all models and use that.
- use
dynamic
as model - split view in shared (extract into separate view) and specific part. Than call shared sub-view with either existing model (if using base class/dynamic) or simply new model constructed based on data in specific model.
Sample of extracting shared portion with inheritance. Using Html.Partial to render shared portion:
class SharedModel { /* Id,...*/ }
class SpecificModel : SharedModel { /* Special... */ }
SpecificView:
@model SpecificModel
@Html.Partial("SharedView", Model)
<div>@Model.Special</div>
SharedView:
@model SharedModel
<div>@Model.Id</div>
Side note: You can specify view name when returning result by using View if view name does not match action name:
return View("MySharedView", model);
回答3:
In ASP.NET MVC4 you have the opportunity not to define a model for the view. This means leave the definition of the model empty (don't use @model MyNamespace.MyClass) and then it will automatically use "dynamic" as model.
Greetings Christian
来源:https://stackoverflow.com/questions/15839623/which-is-the-best-way-to-use-multiple-models-with-sames-properties-and-using-a-u