0

I've got the following cshtml code in my razor view.

<div class="col left-col pull-left">
    @for (int i = 0; i < @Model.NewsResults.Count; i = i + 2)
    {
        NewsResult article1 = @Model.NewsResults[i];
        <div>@i - @article1.Title   @Html.Partial("NewsItemPartial", article1)</div>
    }
</div>

The @i ... seems to tell razor to ouput the data. If I leave the out there, nothing renders.

Please explain how I can do what I have below but without having to use the (before the @i).

3 Answers 3

1

You can tell razor to output HTML by putting the text tag instead of div:

<text>@i - @article1.Title   @Html.Partial("NewsItemPartial", article1)</text>
Sign up to request clarification or add additional context in comments.

Comments

1

Razor is getting confused because it thinks the - is a subtraction operator, and it's trying to subtract Title from i. you could use Mark's method, or you could make it even more localized by putting the <text> block around the -.

@i <text>-</text> @article1.Title   @Html.Partial("NewsItemPartial", article1)

However, it looks to me like you're trying to implement a template output, which MVC already provides a mechanism for, called DisplayTemplates. You should really use those instead of Partials.

1 Comment

The whole line should be it's own display template, and the model should include its position in the list before it reaches view.
0

As has already been mentioned, Razor is considering the - to be a subtraction operator because of its position right after the @i, which is converting it into a C# block.

You can use <text></text> to convert any block (single line or multiline) into a text literal in Razor.

@i <text>-</text> @article1.Title   @Html.Partial("NewsItemPartial", article1)

Or better yet, for a single line (or single character as your example), you can alternatively use the @: operator.

@i @:- @article1.Title   @Html.Partial("NewsItemPartial", article1)

Reference: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.