quitstalin
quitstalin

Reputation: 163

ASP.NET MVC Razor Content Placeholders

Perhaps this has been addressed somewhere else, but I can't find the keywords to search for.

In ASP.NET MVC with the Razor view engine: I have a view which renders with the same if statement repeated numerous times, in different parts of the html. I'm wondering if there's a way to consolidate all of these if's into a single if and set values for placeholders that would save the spot where each of those if's are, like so:

<div>@ph1</div>
<div>@ph3</div>
<div>@ph2</div>

@if(true)
{
    ph1 = "<div>adfad<div>"
    ph2 = "dsfaadfad"
    ph3 = Model.Value
}

This is kind of a stupid example, but I think it makes the point of what I mean.

Upvotes: 2

Views: 3425

Answers (3)

quitstalin
quitstalin

Reputation: 163

@{
    MvcHtmlString ph1 = new MvcHtmlString("");
    MvcHtmlString ph2 = new MvcHtmlString("");
    if (true)
    {
        ph1 = new MvcHtmlString("<div>" + Model.Value + "<div>");
        ph2 = new MvcHtmlString("<div>fsgfdgdfg<div>");
    }
}

@ph1
@ph2

Again, silly usage, but it makes the point.

As was suggested in one of the answers, a nice addition to what I have is to assign a helper. This makes it easier to assign multiple statements without a lot of concatenation.

@helper helper()
{
    <span>@Model.Value</span>
    <div>dsfadsfasdfdfa</div>
}

@{
    MvcHtmlString ph1 = new MvcHtmlString("");
    MvcHtmlString ph2 = new MvcHtmlString("");
    if (true)
    {
        ph1 = new MvcHtmlString("<div>" + Model.Value + "<div>");
        ph2 = new MvcHtmlString(helper().ToHtmlString());
    }
}

@ph1
@ph2

If anybody has better ideas, I'd still be interested.

Upvotes: 1

Erik Philips
Erik Philips

Reputation: 54676

Views shouldn't normally have logic in your views (especially a single helper that is creating html). A better option is to use partial views or display for templtates.

models/[controller]

public class SomeViewModel()
{
  //[UIHint("PhoneNumber")]
  //public string ph1 { get; set; }
  //[UIHint("PhoneNumber")]
  //public string ph1 { get; set; }
  //[UIHint("PhoneNumber")]
  //public string ph1 { get; set; }

  //if these all represent phone numbers, it would be ideal to
  [UIHint("PhoneNumbers")]
  IEnumerable<string> PhoneNumbers { get; set; }
}

views/[controllers]

@model SomeViewModel

@Html.DisplayFor(m => m.PhoneNumbers);

view/shared/DisplayTemplates/PhoneNumbers.cshtml

@model IENumerable<string>

@foreach (string phoneNumber in Model)
{
  <div>@phoneNumber</div>
}

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93494

Your code is fine. You could also use a Razor Helper

http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Upvotes: 2

Related Questions