Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ASP.NET MVC 2 way to to represent same model in two different ways

For instance I have a model X with properties Title(string) and Valid(bool). I need to show same model on two separate pages with different field labels and input controls. E.g. "Title" for title and "Valid" for valid on one form while "Destination" for title and "Returning" for valid on the other.

I guess the easiest way would be to have two different views for the same model. But is it really a MVC way to go?

Thanks

like image 231
Ramunas Avatar asked Aug 12 '10 06:08

Ramunas


3 Answers

Well, let's say you have some View-folder called List, and one called Details - and displaying the Model in the two should be different.

You can create a DisplayTemplates folder within each of the two folders, and create a PartialControl with the same name as your Model, and also strongly type it to your Model.

In your different views you can then do <%= Html.DisplayFor( your model) %> or you can also use the regular <% Html.RenderParital("NameOfPartial", ModelX); %>

Edit To try and approach the original question, maybe this could help you in some way (I posted this as an answer to a different question How to change [DisplayName“xxx”] in Controller?)

public class MyDisplayName : DisplayNameAttribute
{
    public int DbId { get; set; }

    public MyDisplayName(int DbId)
    {
        this.DbId = DbId;
    }


    public override string DisplayName
    {
        get
        {
            // Do some db-lookup to retrieve the name
            return "Some string from DBLookup";
        }
    }
}

    public class TestModel
    {
        [MyDisplayName(2)]
        public string MyTextField { get; set; }
    }

Maybe you could rewrite the custom-attribute to do some sort of logic-based Name-selection, and that way use the same PartialView for both model-variations?

like image 176
Yngve B-Nilsen Avatar answered Sep 20 '22 18:09

Yngve B-Nilsen


Yes, two different Views is appropriate, as you are providing two different VIEWS of your MODEL.

However, are you sure you aren't shoehorning your data into a single model, when in fact it represents a different entity in each case?

like image 29
Jamie Avatar answered Sep 21 '22 18:09

Jamie


Is it really the same model?

If they're two different entities with similar properties then I would create two separate view models. Any commonality could be put in an abstract base class or interface.

If it's the same model but just a different input screen then sure, reuse the model.

I would imagine the first case is probably the one that is relevant here.

like image 20
Matt B Avatar answered Sep 22 '22 18:09

Matt B