开发者

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.


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.


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");
}


Have you tried out Razor Sections.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜