1

I am trying to get the following ternary conditional to work in Asp.Net MVC 3 Razor:

<a href="@Url.Action("TestBrowse", new { page = @(Model.IsLastPage ? Model.PageNumber : Model.PageNumber + 1) })">Next</a>

All of the examples I am finding of using a ternary conditional in Razor have return values which are strings. But here I would like to use an expression (Model.PageNumber + 1) and return a number. Is this possible?

1 Answer 1

4

Drop the @ sign before the value:

<a href="@Url.Action("TestBrowse", new { page = Model.IsLastPage ? Model.PageNumber : (Model.PageNumber + 1) })">Next</a>

Let me just add that in general, Razor doesn't need/want the @ prefix unless it's absolutely necessary, for example:

<div>
@foreach(var value in Model.Values)
{
if(value.Flag)
{
<div>@value.Text</div>
}
}
<div>

Notice that you don't need a second @ sign until you're actually inside the tag, where Razor wouldn't know whether you wanted to display the text "value.Text" or execute it as code. The if statement is assumed to be code. To escape this and write the line "if(value.Flag)" as text you'd need to explicitly say so with the @: prefix.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked. And thanks for the added insights into using Razor. Very helpful.

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.