ASP.NET MVC - Razor和JavaScript

šlj*_*ker 4 javascript razor

如何将javascript放在if块内?

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

我到了bad compile constant value.

GvS*_*GvS 5

$标志不表示Razor切换到Html模式.

将脚本包装在<text>标签中:

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