Possible Duplicate:
Mix Razor and Javascript code
Here is the code I'm trying to run:
// Razor code!
@if (User.Identity.IsAuthenticated) {
// This is Javascript, NOT C#/Razor code. Hence the '@' symbol.
var currentUser = @User.Identity.Name;
} else {
// Also Javascript code!
var currentUser = null;
}
Basically, I want to output this as Javascript if the user is logged in:
var currentUser = @User.Identity.Name;
Or this if the user is logged out:
var currentUser = null;
Well first you will want to change it to something like (remember your quotes around the @User.Identity.Name
):
<script type="text/javascript">
var currentUser = null;
@if (User.Identity.IsAuthenticated) {
<text>
currentUser = '@User.Identity.Name';
</text>
}
</script>
Then add some javascript:
<script type="text/javascript">
if (currentUser != null) {
document.getElementById('loggedInUser').innerHTML = 'Welcome '+ currentUser;
}
</script>
As soon as you start tag in Razor, it switches to markup (including <script>
). If you don't need any tag, use <text>
instead.
If you need quick copy/paste solution, take Tim's or Adam's as both do the job. However, as Razor uses pretty complex algorithms while parsing mix of several languages, it is worth providing Phil Haack's Razor part of quick reference in its entirety (allowed by CC-BY license):
Code Block:
@{ int x = 123; string y = "because."; }
Expression (Html Encoded):
<span>@model.Message</span>
Expression (Unencoded):
<span> @Html.Raw(model.Message) </span>
Combining Text and markup:
@foreach(var item in items) { <span>@item.Prop</span> }
Mixing code and Plain text:
@if (foo) { <text>Plain Text</text> }
Mixing code and plain text (alternate):
@if (foo) { @:Plain Text is @bar }
Email Addresses:
Hi [email protected]
Explicit Expression:
<span>ISBN@(isbnNumber)</span>
Escaping the @ sign:
<span>In Razor, you use the @@foo to display the value of foo</span>
Server side Comment:
@* This is a server side multiline comment *@
Calling generic method:
@(MyClass.MyMethod<AType>())
Mixing expressions and text:
Hello @title. @name.
I left out Razor delegate since there are Razor helpers now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With