开发者

One View for different Models that all inherit from a BaseModel

I want to create one View for different Models that are all inherit from the same BaseModel. But I don´t know which is the right approach.

Why i don´t want to u开发者_开发知识库se different/strongly typed views? Because lets say I will build a lampshop and the basemodel defines a lamp. So all models that inherit the basemodel are lamps with the same baseproperties and 1,2,3 special properties. I think it´s not neccessary to build 30-40 Views for almost the same Models.


As you said all lamps are the same except few additional properties. Imagine that properties as extensions to base class. Base class allows existance of extensions(through LampSpecialProperties), but does not care about their content. Then you could define models like this

public class LampViewModel
{
   public string SomeProperty {get;set}
   public LampSpecialProperties SpecialProperties {get;set;}
}

public abstract class LampSpecialProperties
{ }

public class SomeConcreteLampSpecialProperties : LampSpecialProperties
{
     public string BrightnessLevel {get;set;}
}

In your view, display the lamp base model properties and then the extension properties

@model LampViewModel
... some shared properties    
@Html.DisplayFor(model => model.SpecialProperties)

In Views/DisplayTemplates you could have templates for every concrete implementation of those LampSpecialProperties

@model SomeConcreteLampSpecialProperties
@Html.DisplayFor(model => model.BrightnessLevel)

For another lamp

@model SomeAnotherConcreteLampSpecialProperties
@Html.DisplayFor(model => model.FuelConsumption)// sounds scarry :)

And so forth for all the lamp extensions.

But this all is about your domain and business logic. If your business requires 30-40 model classes anyways, you should create them one by one


Why don't you create a strongly typed view for your base model?

You can call this view, by specifing its name in return View("myViewName", myModel);.

Another option would be to use T4 templates for generating the form fields from the model: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

Then just have to call @Html.EditorModelFor() to generate your html for the model.


You can use viewModels to handle this. In MVC viewModels are classes that are created to (1) provide a strongly typed class to the view and (2) de-couple the view from the model.

In your case you can have a viewA that renders viewModelA and in your controller create viewModelA from any of your models that need to render that view.

This is a good article on the subject: http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/


Could you define a BaseLamp View that will display all of the base properties of your View and then create something like an ExtendedLamp view that renders the BaseLamp view and then its additional fields?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜