gonzalomelov
gonzalomelov

Reputation: 981

MVC4 Razor template like

Hello I have a simple question I think,

I have a cshtml like:

<div id="box">
    @if (model.View == "item1")
    {
        <div id="item1">
            ...
        </div>
    }
    else
    {
        <div id="item2">
            ...
        </div>
    }   
    <div id="itemDescription">
        ...
    </div>
</div>

Where I pass a parameter via the model to display some content depending on the parameter, because the rest of the document is the same in both cases.

Is there another better way to achieve this?

Thanks!

Upvotes: 3

Views: 453

Answers (2)

Mathew Thompson
Mathew Thompson

Reputation: 56429

Your approach is fine if there isn't much in those two div's. Otherwise, create two partial views to help keep things tidy:

@if (model.View == "item1")
{
    @Html.RenderPartial("Item1");
}
else
{
   @Html.RenderPartial("Item2");
} 

Upvotes: 4

Ant P
Ant P

Reputation: 25221

Not really; this is a perfectly good way of doing things. If the div id always matches the value of model.View, you could shorten it to this:

<div id="box">
    <div id="@(model.View)">
        ...
    </div>  
    <div id="itemDescription">
        ...
    </div>
</div>

Otherwise, your approach is fine. As per von v's comment, you might want to look into partial views if the contained markup is long-winded (or you need to repeat the logic in multiple places):

http://www.asp.net/mvc/videos/mvc-2/how-do-i/how-do-i-work-with-data-in-aspnet-mvc-partial-views

Upvotes: 3

Related Questions