Domanda

I have a a View with three news boxes: NewsOfTheDay, NewsOfTheWeek, NewsOfTheMonth. In my model I have this same three properties. Now my code looks like this:

@{var news=Model.NewsOfTheDay;}
<div class="newsbox">
    <h2>@(news.Title)</h2>
    <p>@(news.Text)</p>
<div>

<!--other html code-->

@{var news=Model.NewsOfTheWeek;}
<div class="newsbox">
    <h2>@(news.Title)</h2>
    <p>@(news.Text)</p>
<div>

So, as you see, I'm repeating html code here, there is more duplication, removed for clarity. Now, I could do some magic with partial views (Html.Action) but then I'll have to split my model.

Is there something equivalent to this: @RenderBox("NewsItem",Model.NewsOfTheWeek)

È stato utile?

Soluzione

I would probably go with the partial view, but you could also use a custom HtmlHelper method. The key would be to have each of the properties actually be of the same type (or implement the same interface) because the type of the model would need to be the same. You could use dynamic for the model type, but that seems overkill since they do seem to have the same properties.

 @Html.Partial("_NewsItem",Model.NewsOfTheWeek)

where _NewsItem.cshtml is

@model NewsItem

<div class="newsbox">
    <h2>@Model.Title</h2>
    <p>@Model.Text</p>
<div>

and your NewsItem class is

public class NewsItem
{
    public string Title { get; set; }
    public string Text { get; set; }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top