I want to do this in my Razor view:
@foreach (Customer cust in Model.Customers)
{
<tr data-custid="@customer.GetIdAsText()">
@Html.RenderPartial("CustomerListTableRow", cust)
</tr>
}
As far as I understand, this should work. The foreach block contains a <tr>…</tr>. Inside that, it is in markup mode, so I need @ to switch to C# mode. The problem is that apparently the variable cust loses its type info (and value?), so it complains that it cannot cast void to object, which RenderPartial expects.
I got it working like this:
@foreach (Customer cust in Model.Customers)
{
@:<tr data-custid="@customer.GetIdAsText()">
Html.RenderPartial("CustomerListTableRow", cust);
@:</tr>
}
But aside from looking puke ugly, if I let VS beautify the code, it mucks it up like this:
@foreach (Customer cust in Model.Customers)
{
@:<tr data-custid="@customer.GetIdAsText()">
Html.RenderPartial("CustomerListTableRow", cust); @:</tr> }
Nice, huh? 🙂
So, why doesn’t the first solution work? How should I write it?
Html.RenderPartial()is a void method and hence it must be enclosed it with a{ }block:What you are definitely looking for is
Html.Partial(), which returns anMvcHtmlString, and it can be used like this: