šljaker
šljaker

Reputation: 7374

ASP.NET MVC - Razor and JavaScript

How can I put javascript inside if block?

@if(TempData["notification-message"] != null) {
        $('#notification').jnotifyAddMessage({
            text: '@TempData["notification-message"]',
                permanent: false
                            });
}

I'm getting bad compile constant value.

Upvotes: 4

Views: 1055

Answers (1)

GvS
GvS

Reputation: 52501

The $ sign does not signal Razor to switch to Html mode.

Place the script wrapped in<text> tags:

@if(!string.IsNullOrEmpty((TempData["notification-message"] as string))) {
     <text>
        $('#notification').jnotifyAddMessage({
            text: '@TempData["notification-message"].ToString(),
                permanent: false
                            });
     </text>
}

Upvotes: 5

Related Questions