Kjell Rilbe
Kjell Rilbe

Reputation: 1509

Weird Razor nesting foreach (...) { <tr> @Html.... </tr> }

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?

Upvotes: 1

Views: 699

Answers (2)

Paolo Moretti
Paolo Moretti

Reputation: 55994

Html.RenderPartial() is a void method and hence it must be enclosed it with a { } block:

@{Html.RenderPartial("CustomerListTableRow", cust);}

What you are definitely looking for is Html.Partial(), which returns an MvcHtmlString, and it can be used like this:

@Html.Partial("CustomerListTableRow", cust)

Upvotes: 4

maaizle
maaizle

Reputation: 135

I think this should work,

@foreach (Customer cust in Model.Customers)
{
    <tr data-custid="@customer.GetIdAsText()">
        @Html.RenderPartial("CustomerListTableRow", cust);
    </tr>
}

Depending on the version of MVC you are running.

Can you provide more details on the error?

Upvotes: 0

Related Questions