简体   繁体   中英

Unable to call a Javascript method from a Razor 'IF' statement

Question background:

I am attemting to check if a user is logged in to my site when a view is rendered.

The issue:

Currently I set the users username to a ViewBag property in a Controller then access this in its respective View. The issue I'm facing is the IF statement in my Razor syntax dosen't seem to be checking the ViewBag.userName property and in-turn is not then calling the JavaScript method to set the Inner HTML of a button with the users name.

As a side note I have - as a test - set the ViewBag property to a h3 tag just to make sure the users name is being passed to the view which it is.

The code:

My controller where the username is set:

ViewBag.userName = Session["userName"];

The View:

Check the status of the ViewBag property userName , if it not null ie a users has logged in, then Call the ShowUsersName method to set the value to a buttons inner HTML.

@if (ViewBag.userName != null)
{
    <script>
       var userName= @ViewBag.userName;

        ShowUsersName(userName);
    </script>
}

ShowUsersName method:

<script type="text/javascript">

var ShowUsersName = function (userName) {

    var html = '<span class="glyphicon glyphicon-user"></span> Hi, '+ userName +'"<strong class="caret glyphicon glyphicon-triangle-bottom"></strong>';

    document.getElementById("userButton").innerHTML = html;

};
</script>

I don't think simply putting a script tag inside an if statement will cause javascript to run. You need to Bind this to on load of the body (or some other event)

<body onload='jsFunction()'>

if you're using jQuery you can have a script section with:

$(document).ready(function() {  
   //your code
});

one thing you could do is in your if statement create a hidden element or input that has the username value:

<div id='user-name' style='display:none;'>
@if (ViewBag.userName != null)
{
    @ViewBag.userName
}
</div>

and in your jQuery (if you're using jQuery):

$(document).ready(function() {  
   var userName = '';
   userName = $('#user-name').text();
   if (userName != '') {
    //your code if userName is not empty
   }
});

something along these lines. This is just a quick example, you may find an alternative way of doing this

Make sure that your viewbag is not null. You could also try and remove the if statement to see if it renders the script. To test the content of the viewbag you could do:

<h1>@ViewBag.userName</h1> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM