Konrad
Konrad

Reputation: 4792

Arrange blocks of code in an MVC 3 view

I have a complex View (cshtml) in my MVC3 project. Depending on different variables, the parts of this code must be shown in a different order. How can I separate blocks of Razor/HTML code and "include" them at the proper position? Looking for something like that:

@{ CODEBLOCK 1
...
}

@{ CODEBLOCK 2
...
}

@if (bla==1) {
    include CODEBLOCK 1
    include CODEBLOCK 2
} else {
    include CODEBLOCK 2
    include CODEBLOCK 1
}

I don't want to use HtmlPartial, since I don't want to pass all vars, the model and other stuff to it.

Upvotes: 2

Views: 313

Answers (4)

itsmatt
itsmatt

Reputation: 31416

While I like Morten Christiansen's approach, another approach that I'll just throw out as a way to "move stuff around" on the page would be to use jQuery to adjust where things are.

Assuming a view with something like this:

<div id = "div1">
   Something
</div>
<div id = "div2>
   Something Else
</div>

and then some jQuery to determine whether to do the swap:

if (someCondition)
{
   $('#div2').insertBefore('#div1');
}

Again, I just throw that out there as one other possible way to adjust which comes first, but I certainly like Morten's idea better.

Upvotes: 0

Morten Christiansen
Morten Christiansen

Reputation: 19580

You can use helper methods:

@helper CodeBlock1()
{
    ...
}

@helper CodeBlock2()
{
    ...
}

@if (bla==1) {
    CodeBlock1();
    CodeBlock2();
} else {
    CodeBlock2();
    CodeBlock1();
}

As a bonus, it's type safe and allows arguments.

Upvotes: 7

Manual5355
Manual5355

Reputation: 982

What about layout sections?

http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

@section CODEBLOCK1 {
...
}

@section CODEBLOCK2 {
...
}

@if (bla==1) {
    @RenderSection("CODEBLOCK1");
    @RenderSection("CODEBLOCK2");
} else {
    @RenderSection("CODEBLOCK2");
    @RenderSection("CODEBLOCK1");
}

Upvotes: 1

Charandeep Singh
Charandeep Singh

Reputation: 972

Have you tried out Razor Sections.

Upvotes: 0

Related Questions