我有Razor语法和jQuery的问题,我正在尝试将一些项目附加到空表中。 这是代码
@{
if (@ViewData["a"] != null)
{
var tab = @ViewData["a"] as List<string>;
foreach(var sp in @tab)
{
<text>
$('#files-table').append(@Html.Raw(@sp));
</text>
}
}
}
@sp
变量就像(我在这里格式化):
<tr>
<td>
<a class='some-class' my-type='abc' my-id='1'
target='_blank' href='/Home/a'>name123</a>
</td>
<td>
<label class='del' f-id='abc'>lorem</label>
</td>
</tr>
该表仍为空。我尝试了很多选项,例如.append('@Html.Raw(@sp)')
,.append(@Html.Raw(sp))
等,但没有成功
答案 0 :(得分:3)
只有在html和代码之间进行转换时才应使用@
。否则,当你在一个或另一个时,你不需要它。话虽如此,试一试:
@if (ViewData["a"] != null)
{
var tab = (List<String>)ViewData["a"];
foreach (var sp in tab)
{
<text>
$('#files-table').append('@Html.Raw(sp)');
</text>
}
}
Screenshot http://img849.imageshack.us/img849/3250/razordemo.png
请注意,我还在引号中附加了Html.Raw
的结果。您可能需要做更多工作来保护sp
中没有可能会干扰包装报价的引号。
我不得不问,如果你有前期数据并且能够被渲染,你为什么要将它交给客户端进行渲染(更容易出错并同时产生延迟和依赖性)而不是自己渲染?它看起来效率不高......
答案 1 :(得分:1)
为什么要在控制器中构建行? 尝试返回包含要在表中显示的数据的对象列表,然后在视图中构建html表,如下所示:
@if (ViewData["a"] != null)
{
var list = (List<YourObject>)ViewData["a"];
foreach (YourObject item in list)
{
<tr>
<td>
<a class='some-class' my-type='abc' my-id='1' target='_blank' href='/Home/a'>@item.name</a>
</td>
<td>
<label class='del' f-id='abc'>@item.phone</label>
</td>
</tr>
}
}
另外,不要使用ViewData,而是考虑使用自定义模型将数据从控制器发送到视图。