Lerato
Lerato

Reputation: 31

Razor view error mvc asp.net

I'm at the beginner level about mvc apps so I would like some help please.

I'm trying to embed c# with jquery to test a condition of if a user.identity is authenticated on document.load but I'm getting cs1001(Identifier expected).

$(document).load(function () {

            if (@{User.Identity.Name != "Someone"}){
                alert("Something");
            }
        });

Upvotes: 0

Views: 194

Answers (2)

adiga
adiga

Reputation: 35202

You can do something like this:

@if (User.Identity.Name != "Someone"){
   @:alert("Something");
}

or

@if (User.Identity.Name != "Someone"){
   <text>alert("Something");</text>
}

or

var identityName = @Html.Raw(Json.Encode(User.Identity.Name));

if (identityName  != "Someone"}){
    alert("Something");
}

or

if ("@User.Identity.Name" != "Someone"){
    alert("Something");
}

The first 2 are C# if conditions and are computed server side. While the last 2 are javascript if blocks which will be run client side.

Upvotes: 0

Imad
Imad

Reputation: 7490

Remove curly brackets from if

if (@User.Identity.Name != "Someone"){
    alert("Something");
}

Upvotes: 1

Related Questions