如何在MVC3剃刀混合HTML和C#code? [英] How to mix HTML and C# Code in MVC3 with Razor?
问题描述
我想显示应触发一类造型目的的项目列表。这个想法是创建一个foreach循环将通过循环所有 MyObj中
在模型中。
I am trying to display a list of items that should toggle a class for styling purposes. The idea is to create a foreach loop that will cycle through all the myObj
in the Model.
我尝试以下code不工作(因为我做错了)
I tried the following code which does not work (because I'm doing it wrong)
@{ int i = 2;
foreach(var myObj in Model)
{
if (i % 2 == 0)
{
<div class="class1">
}
else
{
<div class="class2">
}
Html.Partial(...);
</div>
i += 1;
}
}
什么是实现这一目标的正确方法?
What is the proper way to accomplish this?
更新
结果
我也试过以下code,虽然编译,不渲染中的任何HTML code(我敢肯定有在模型对象)。
Update
I also tried the following code that, although compiles, does not render any HTML code within (and I'm sure there are objects in Model).
@{ int i = 2;
foreach(var myObj in Model)
{
if (i % 2 == 0)
{
@:<div class="class1">
}
else
{
@:<div class="class2">
}
Html.Partial(...);
@:</div>
i += 1;
}
}
这是被称为局部类
<div class="class">
<div class="class2">
@if (string.IsNullOrEmpty(var))
{
@var2
}
else
{
@var
}
</div>
<div class="class3">
@var3
</div>
</div>
<div class="class4">
<p>var4</p>
<ul class="class5">
<li>element1</li>
<li>element2</li>
</ul>
</div>
我很抱歉,我不能发布的实际名称和变量。
I'm sorry I can't post the actual names and variables.
推荐答案
让我们先从改善你的code。
Let's start with improving your code.
-
改进步骤1:
Improvement step 1:
@foreach(var myObj in Model.Select((model, index) => new { model, index }))
{
<div class="class@(myObj.index % 2 == 0 ? "1" : "2")">
@Html.Partial("_Foo", myObj.model)
</div>
}
改进步骤2(使用类的自定义HTML助手):
Improvement Step 2 (using a custom HTML helper for the class):
@foreach(var myObj in Model.Select((model, index) => new { model, index }))
{
<div class="@Html.MyClass(myObj.index)">
@Html.Partial("_Foo", myObj.model)
</div>
}
在这里MyClass的定义是这样的:
where MyClass is defined like this:
public static string MyClass(this HtmlHelper html, int index)
{
return (index % 2 == 0) ? "class1" : "class2";
}
改进步骤3,它是本领域的状态(使用模板化剃刀代表):
@Model.List(
@<div class="@item.MyClass">
@Html.Partial("_Foo", @item.Model)
</div>
)
其中列表
扩展方法是这样的:
public class ModelHolder<T>
{
public T Model { get; set; }
public string MyClass { get; set; }
}
public static class RazorExtensions
{
public static HelperResult List<T>(
this IEnumerable<T> items,
Func<ModelHolder<T>, HelperResult> template
)
{
return new HelperResult(writer =>
{
foreach (var item in items.Select((model, index) => new { model, index }))
{
var myClass = item.index % 2 == 0 ? "class1" : "class2";
template(new ModelHolder<T> { Model = item.model, MyClass = myClass }).WriteTo(writer);
}
});
}
}
我投了改进3号远低于原来的foreach循环更好,更简洁。
I vote for improvement number 3 which is far better and more concise than the original foreach loop.
这篇关于如何在MVC3剃刀混合HTML和C#code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!