0

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)

2
  • Not an MVC developer, but why wouldn't you just render a partial view three times and have whatever type NewsOfTheWeek is as the model type? Commented Jan 13, 2013 at 1:12
  • I could, as I said, but then I'll need separate queries for every news type, and I must (prefer to) get them in one call. Commented Jan 13, 2013 at 1:15

1 Answer 1

3

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.