2

Trying to populate table data with:

        @foreach (var mc in Model.McList)
        {
            <tr>
                <td>
                    @(@mc.Amount != null ? @mc.Amount @@ @mc.Price : null)
                </td>
            </tr>
        }

but stuck in razor syntax errors:

expect :

expect )

or ambiguous invocation: void Write

Amount is int? nullable type.

@(@mc.Amount != null ? @mc.Amount : null) //works only with one property
@if (@mc.Amount != null) {@mc.Amount <text>@@</text> @mc.Price} //works
@if (@mc.Amount != null) {@mc.Amount @@ @mc.Price} //error
@if (@mc.Amount != null) {@mc.Amount @:@@ @mc.Price} //error

is it shorter way to check for null value without if?

4
  • what are the specific errors? I'd say d.Price is not int (decimal) Commented Feb 13, 2014 at 19:52
  • Of course Price is decimal. And i want to achieve similar output: e.g. 120 @ 30.50 Commented Feb 13, 2014 at 20:05
  • Would HTML.Raw() help here? Commented Feb 13, 2014 at 20:14
  • Does this work? @(mc.Amount != null ? mc.Amount.ToString() + Html.Raw("@") + mc.Price.ToString() : "") Commented Feb 13, 2014 at 20:23

2 Answers 2

1

I don't think that's possible. If you must do that in one line, the closest I get is:

@(@mc.Amount != null ? string.Format("{0} @ {1}", mc.Amount, mc.Price) : null)

I'd probably never do that myself!

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

3 Comments

So looks like IF operator is only option there!?
Don't know, but what's wrong with an IF operator? Is't the construct <exp> ? <exp> : <exp> just syntactic sugar for an if/else? And besides, its not like we can live without IF statements :)
For me no problem with IF, just looking for shortened code :) As i use that construct in c# often.
0

I think you're trying to make something that looks like this:

5 @ 20

If so, you need to keep in mind that everything between @( and ) is pure C# code; what you need to do is something like this:

@(mc.Amount != null ? string.Format("{0} @ {1}", mc.Amount, mc.Price) : "")

1 Comment

Tnx, for opening my eyes. Now i get it better - @ usage in razor.

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.