Evaluate Razor variable in javascript - javascript

I need to evaluate a razor variable inside a JavaScript function. Given the following code:
#{var unseenNotificationsExist = false;}
#foreach(var notification in viewModel)
{
if (notification.WasSeen == false)
{
unseenNotificationsExist = true;
break;
}
}
I need to evaluate the unseenNotificationsExist variable in JavaScript like this:
if(#unseenNotificationsExist == true)
$('#unseenNotifCount').addClass('notifNotSeen');
However, when I debug the JavaScript code, I get this:
if(True == true)
and also I get the following error:
Uncaught ReferenceError True is not defined

var unseenNotificationsExist = #(unseenNotificationsExist?"true":"false") ;
//the line above must be part of your view
if(unseenNotificationsExist === true)
$('#unseenNotifCount').addClass('notifNotSeen');
//this can be part of your js file or alternatively and less
//preferably part of your view

I found a workaround: I added this
var True = true
Now, in javascript there is a variable "True" defined and the evaluation comes down to True == true, which returns true.

I prefer to use Json.Encode , whenever i want to convert the model data to JSON objects or JSON variables .
For converting an object(dto) of model to javascript
var accountDto = #Html.Raw(Json.Encode(#Model.AccountDto))
For converting a (bool)property of model
var isTrue = #Json.Encode(Model.IsTrue)

If you want to not have the the JavaScript rendered, use Daniele's suggestion.
If you insist on making the comparison in JavaScript:
if(#unseenNotificationsExist.ToString().ToLower() === true)

You tried with:
if('#unseenNotificationsExist' === 'True')
$('#unseenNotifCount').addClass('notifNotSeen');

try using
if('#unseenNotificationsExist')

Related

Check viewbag null in javascript under razor code

I pass null to RepresentativeTypesList viewbag but I'm trying to understand why the line
if ('#representativeTypesList' != null)
is not evaluated correctly and the cursor runs straight to the Html.Raw part of the view below. I believe I have put the # escape chars correctly. Any help would be very much appreciated.
#{
var representativeTypesList = #ViewBag.RepresentativeTypesList;
}
#section Header {
<script type="text/javascript">
if ('#representativeTypesList' != null)
{
var array1 = '#Html.Raw(
Json.Encode(
((IEnumerable<RepresentativeTypesModelView>)ViewBag.RepresentativeTypesList).Select(item => new
{
itemValue = (item.Value == null ? "" : item.Value),
itemText = (item.Name == null ? "" : item.Name)
})
)
)';
hdninput1 = $("#txtSalesReps_hdn");
dropdown1 = $("#selSalesReps");
dropdown1.append($("<option />").val('default').text('-- '#lbls.lblSelectOption' --'));
if (array1.length > 0)
{
$.each(array1, function() {
dropdown1.append($("<option />").val(this.itemValue).text(this.itemText));
});
}
}
</script>
}
Potentially remove the tick marks on both sides of #representativeTypesList, could be that it's evaluating the string as being not null instead of evaluating the variable as being null.
Razor is only used to create the initial markup. Once the page is rendered (i.e., once you are running javascript in the client, instead of preparing it on the server), '#representativeTypesList' will be seen as a hardcoded string as it existed when it was rendered, it won't be seen as a javascript variable.
Instead, why not declare a javascript variable and set its initial value using Razor:
var repTypesList = #representativeTypesList;
if (repTypesList !== null) {
...
}
Then you can change the value at runtime, etc.
Can you simply pass the ViewBag object into the code without casting it to a variable first? That should work unless there is a specific reason you are needing to do this. As Elemental Pete stated Razor is used only to create the initial mark up. Razor is NEVER sent to the browser. It is processed on the server. It then renders whatever it is told to render in the HTML,CSS,JS code and that is then sent to the browser. The browser then runs the JS code. Think of your code that way and I would try replacing
if ('#representativeTypesList' != null)
with
if (#ViewBag.RepresentativeTypesList != null)
Hope that helps!
Jason
The solution was given here Using Razor within JavaScript. Because my code is inside a js section, it needs to be surrounded with "text" tags. Thanks.
I just tried the following in my code and it worked. Compare this to your code.
In the Controller:
public ActionResult SomeMethod(int id)
{
ViewBag.RepresentativeTypesList = null;
}
In the View:
#{
var representativeTypesList = ViewBag.RepresentativeTypesList;
}
#section Header {
<script type="text/javascript">
if ('#representativeTypesList' != null)
{
if (array1.length > 0)
{
$.each(array1, function() {
dropdown1.append($("<option />").val(this.itemValue).text(this.itemText));
});
}
}
</script>
}
I had to modify the code in the if statement as I did not have some of the objects that you had but when I ran this it jumped passed the if statement and did not run any of it.
Let me know if you have any questions!
Jason
Also if this or any solutions to questions you have on here works or help out please make sure you mark the answer as the correct one if it is your questions or if not but the answer is beneficial please click the up arrow to indicate that it was useful. Thank You! :)

Referencing a number in a JavaScript multidimensional object

The code I have below uses a number as a dataset in a JavaScript object:
spacenum = spacedetails[1];
//Create object for space number
if(spacenum in spaceobj['P1'] == false){
spaceobj['P1'][spacenum] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
}
spaceobj['P1'][spacenum]['Vacant'] = spacedetails[2];
spaceobj['P1'][spacenum]['Name'] = spacedetails[3];
spaceobj['P1'][spacenum]['Number'] = spacedetails[4];
spaceobj['P1'][spacenum]['Apartment'] = spacedetails[5];
This code goes around in a loop so 'spacenum' starts at 1 and goes up to the late 100s.
I am trying to access the data like so:
console.log(spaceobj.P1.11.Vacant);
However, the '11' is throwing up errors. I've tried brackets and quotes without any luck.
How can I access the data I want using a number?
In javascript '11' is not a valid variable name. However, because of its dynamic nature you can use:
console.log(spaceobj.P1["11"].Vacant);
Alternatively, one can also use:
console.log(spaceobj["P1"]["11"].Vacant);
Actually your line code below is undefined
spaceobj['P1']
Be sure your spaceobj['P1'] = false; has value
spacenum = 11;
spaceobj = [];
spaceobj['P1'] = false;
spaceobj['P1'][spacenum]= 'A';
spaceobj['P1'][spacenum]= 'B';

javascript passing the result of a boolean comparison confusion

I've been working through some text book to learn web development and i've become confused on an example. The example creates a meter element and fills it with some attributes. There is then some javascript to check for browser support for the tag. The part where i'm confused is after the first expression returns either true or false for the support, shouldn't there be a check for if true or false was returned on the following if statement? also as an aside, when the create element builds the element does is give it default values, or grab values from an existing meter in the html.
The check for support is as follows.
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
the next part that builds the meter if the support isn't found is below. This is where i become confused as it seems to take either value and continue without checking if it was true or false.
if (noMeterSupport()) {
var fakeMeter, fill, label, labelText, max, meter, value;
value = meter.attr("value");
meter = $("#pledge_goal");
max = meter.attr("max");
labelText = "$" + meter.val();
fakeMeter = $("<div></div>");
fakeMeter.addClass("meter");
label = $("<span>" + labelText + "</span>");
label.addClass("label");
fill = $("<div></div>");
fill.addClass("fill");
fill.css("width",(value / max * 100) + "%");
fill.append("<div style='clear:both;'><br></div>");
fakeMeter.append(fill);
fakeMeter.append(label);
meter.replaceWith(fakeMeter);
}
The body of the if is only executed if noMeterSupport() returns true. The condition in an if statement requires something "truthy", i.e. something that can be interpreted as true or false. Since the function returns a boolean value, that is sufficient. (See first Google hit for truthiness javascript, which is a good explanation.)
EDIT: Forgot about your second question. When a new element is created with document.createElement, it does indeed get default values. In your example, the default value of max for a <meter> is 1.
if (noMeterSupport()) { checks the return value. It means exactly the same as this:
var supported = noMeterSupport();
if(supported) {
I hope that I understand your question correctly and will try to answer it.
So you would expect something like this:
if (noMeterSupport() == true)
Actually, this is equivalent to this:
if (noMeterSupport())
And if you want to check false:
if (noMeterSupport() == false)
This is equivalent to:
if (!noMeterSupport())
This statement will make the function either return true or false:
return(document.createElement('meter').max === undefined)
basically it would be synonymous with writing:
if(document.createElement('meter').max === undefined) {
return true;
} else {
return false;
}
That makes the value of noMeterSupport() either true or false.
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
noMeterSupport returns the result of the comparison document.createElement('meter').max === undefined.
The comparison will be either true or false, ok?
So, now, when you do
if (noMeterSupport()) { /*then do something*/}
is like saying
if (/*the result of noMeterSupport() is true*/) {/*then do something*/}
So, this if statement will only run if noMeterSupport returns true
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
This section of code is not actually doing the check, it is defining a function called noMeterSupport.
The code is not actually run until the function is called. It is called by adding () to the function name.
noMeterSupport()
Your if() statement is where it is being called as it the brackets.
You expect a boolean condition inside the if statement:
if(<boolean_condition>)
{
...
}
The noMeterSupport() is actually returning true or false, so the
if(noMeterSupport())
is converted to if(true) or if(false)
depending on the result of the document.createElement('meter').max === undefined evaluation.
You are receiving a boolean condition and the if statement works fine.
As a beginner, there's two points to quickly learn in programming :
The comparison operators == and === not only do the comparison, but returns in fact the result of this comparison (you can place it in var to test)
var bool = 1 === 2;
console.log(bool); // will print false
The test if(boolean === true) is equivalent to if(boolean), and the test if(boolean === false) is equivalent to if(!boolean)

Javascript comparing boolean value to True

I am trying to compare a database (SQL) value (which is being returned correctly) to the boolean value 'true'. If the database bit value is = true then I want a div element to become visible, else stay hidden.
<script language="javascript">
window.onload= function show_CTL() {
if(<%=_CurrentUser.IsCTL%> == true){
document.getElementById('CTL').style.visibility = "visible";
} else{
document.getElementById('CTL').style.visibility = "hidden";
}
}
</script>
However I am getting the error, Javascript: 'True' is undefined.
I have tried many combinations of <%=_CurrentUser.IsCTL%> == 'true' or "true" or true or "True" or 'true' and even the === ... but all give me the same error message.
Any insights on how to resolve this issue will be greatly appreciated.
I have such comparisons successfully before with integer values such as:-
window.onload= function show() {
if(<%=_CurrentUser.RoleKey%> == 1 || <%=_CurrentUser.RoleKey%> == 2)
document.getElementById('enr').style.visibility = "visible";
else
document.getElementById('enr').style.visibility = "hidden";
}
Do this:
if("<%=_CurrentUser.IsCTL%>" === "True")
<%=_CurrentUser.IsCTL%> is returning True. So wrap it with string and compare them instead. Notice the '===' instead of '=='.
In
if(<%=_CurrentUser.IsCTL%> == true)
I think <%=_CurrentUser.IsCTL%> is getting evaluated to True before the code is seen by the browser.
The browser will see this as
if(True == true)
True does not make a lot of sense to the browser, thats why the error. For this true to be treated as a boolean, try one of this:
if(new Boolean('<%=_CurrentUser.IsCTL%>') == true)
or
if(new Boolean('<%=_CurrentUser.IsCTL%>'))
This has gotten me before as well. ASP.NET will return True for a boolean which is true. You have to make it a string and then compare it to the string version == "True" in order to get a proper conditional statement.
Conversely, you could also just make a variable in javascript
var True = true;
You need to convert your native boolean value to the string "true" before output. So, assuming ASP.NET MVC, I believe it looks like:
<%=_CurrentUser.IsCTL ? "true" : "false"%>

How can I set an if the query string is does come up as something other than

How can I make a javascript if function where if the query string does show as something other than undefined. Here is the code:
var getQueryString = window.location.href.split("?")[1];
alert(getQueryString);
Basically I wanted to do an if function in javascript. Here is the code:
if (getQueryString = 1){
//add code
}
How can I set my javascript function?
I would use location.search and check it's length instead of your approach.
if (window.location.search.slice(1).length > 0) {
doSomething();
}
Currently, your code will always execute because you're setting getQueryString to 1 instead of comparing it. Even if you were comparing it, it would still be false since getQueryString is a string and not a number.
The bellow code should work for you
var getQueryString = window.location.href.split("?")[1];
if (typeof getQueryString !== 'undefined')
{
//Your code goes here
} else [
alert("Query String not set");
}

Categories

Resources