我想在Razor视图中执行此操作:
@foreach (Customer cust in Model.Customers)
{
<tr data-custid="@customer.GetIdAsText()">
@Html.RenderPartial("CustomerListTableRow", cust)
</tr>
}
据我了解,这应该有效。 foreach块包含&lt; tr&gt; ...&lt; / tr&gt;。在里面,它处于标记模式,所以我需要@切换到C#模式。问题是显然变量cust丢失了它的类型信息(和值?),所以它抱怨它无法将void转换为对象,RenderPartial期望它。
我得到了这样的工作:
@foreach (Customer cust in Model.Customers)
{
@:<tr data-custid="@customer.GetIdAsText()">
Html.RenderPartial("CustomerListTableRow", cust);
@:</tr>
}
但除了看起来丑陋之外,如果我让VS美化代码,它会像这样捣乱:
@foreach (Customer cust in Model.Customers)
{
@:<tr data-custid="@customer.GetIdAsText()">
Html.RenderPartial("CustomerListTableRow", cust); @:</tr> }
好的,对吧? : - )
那么,为什么第一个解决方案不起作用? 应该如何我写它?
答案 0 :(得分:4)
Html.RenderPartial()
是一个void方法,因此必须用{ }
块将其括起来:
@{Html.RenderPartial("CustomerListTableRow", cust);}
您肯定要寻找的是Html.Partial()
,它会返回MvcHtmlString
,并且可以像这样使用:
@Html.Partial("CustomerListTableRow", cust)
答案 1 :(得分:0)
我认为这应该有用,
@foreach (Customer cust in Model.Customers)
{
<tr data-custid="@customer.GetIdAsText()">
@Html.RenderPartial("CustomerListTableRow", cust);
</tr>
}
取决于您正在运行的MVC的版本。
您能提供有关错误的更多详细信息吗?