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! :)
Related
i try to detect null this way
if(!$(this))
{
alert('here is null');
}
OR
if($(this)===null)
{
alert('here is null');
}
but still no luck.
here is partial code
$elements.each(function(){
//alert($(this).html());
var $item = $('<li />').append($(this));
if(!$(this))
{
alert('here is null');
}
//alert($item.text());
$list.append($item);
});
anyone can see full code from here https://jsfiddle.net/tridip/41s1pq3a/12/
edit
i was iterate in td's content. td has some link and text. i was trying to wrap each text and link inside li. so iterate this below way. code is working but some time it is also showing null which i need to detect.
i am looking for way not consider any null or empty.
here is the code
var $elements = $('.webgrid-footer td').contents()
.filter(function() {
return this.nodeType === 3 || this.nodeType === 1; // 1 means elements, 3 means text node
});
var $list = $('<ul />');
$elements.each(function(){
//alert($(this).html());
var $item = $('<li />').append($(this));
if(this===null)
{
alert('here is null');
}
//alert($item.text());
$list.append($item);
});
//alert($list.html());
$('#dv').append($list);
see this line var $item = $('<li />').append($(this)); it is getting some time empty or null which i do not want tp consider. if anyone knows it how to handle this situation then share the idea. thanks
$(null) is an empty jQuery object, not null. And all objects are truthy.
If you want to test null, use this === null. You don't need jQuery for this.
However, I don't see why do you expect this to be null sometimes. Instead, it seems you want to ignore whitespace text nodes.
var $elements = $('.webgrid-footer td').contents().filter(function() {
return (this.nodeType === 3 && $.trim(this.nodeValue) !== '')
|| this.nodeType === 1;
});
$(this) will never be either null or falsey, because jQuery always returns an object reference, which is not null or falsey.
In strict mode, it's possible for this (not $(this)) to be null. In loose mode, it isn't; attempts to make this be null will cause this to be a reference to the global object.
So it may be that you want to test this, not $(this). But only in strict mode. In loose mode, bizarrely, you'd want if (this == window) to be your "null" test.
Having said that, $elements is clearly meant to be a jQuery object, and I'm not immediately thinking of a way to to create a jQuery objct with nulls in through the public API. (It's easy if you muck about with the internals...)
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");
}
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')
I've written a bit of JavaScript that reads the referring URL of a page and loops through an object to check for strings such as "google", "msn", "bing" etc. The resulting value is stored in a variable which is then passed to a server. Now this all works perfectly but my question is around detecting traffic directly to a site (i.e. people typing the URL in the address bar). How can I detect this?
I was thinking, that I could do something like:
var refURL = document.referrer;
var serverVar = "";
if (refURL === "") {
serverVar = 'direct traffic';
}
Should I be checking for "" (i.e. blank) or should I be checking if refURL is null?
If you dont want to do the way you are comparing now as in your code, You could use:
//check for blank, null or undefined
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var refURL = document.referrer;
var serverVar = "";
if (isBlank(refURL)) {
serverVar = 'direct traffic';
}
Hope it helps
Just use if(!document.referrer) {}
My function to implement the search is below. The issue I have is I need to track what rows I have to go through to find the URL. I'm building a navigation "widget" and I need it to expand to the correct place based on the URL. Seeing as the URL could be N rows deep, I need a method to track the rows that it passed through.
E.G: row[1].tree.row[3].tree.row[0] , this way I know to expand the navigation for the second element, then the fourth element, then highlight the first element in that list.
The issue is with the rowNum = rowNum+"x"+x; that I pass back to the function. I think I might be overtired when I thought that would work, I didn't think it through.
Suggestions?
Thanks!
I had another question out there about this same function, but this question is different. Is it bad form to submit an additional question?
function lmIntra_LeftNavBuilder_findURL(url)
{
return lmIntra_LeftNavBuilder_searchJson(jsonLNav.tree[0],url,null);
}//end findURL
function lmIntra_LeftNavBuilder_searchJson(tree,url,rowNum)
{
if(rowNum == null)
{
rowNum="";
}
for(var x=0; x<=tree.rows.length-1;x++)
{
var cururl = "";
if(typeof tree.rows[x] ==="undefined")
{
cururl="";
}else
{
var cururl = tree.rows[x].url;
}
if(url == cururl )
{
//return tree.rows[x].title;
return rowNum + " treeDepth:"+tree.pos;
}//end if
else
{
if(typeof tree.rows[x]!= "undefined")
{
if(typeof tree.rows[x].tree.rows != "undefined")
{
rowNum = rowNum+"x"+x;
var t = lmIntra_LeftNavBuilder_searchJson( tree.rows[x].tree,url,rowNum);
if (t) return t;
}//end if
}//end if typeof tree.rows[x].tree!= "undefined"
}//end else
}//end for
}//end searchJson
Here's a simpler json object. It's fully formed, it just doesn't have the depth. The full one is 38K characters, so I'll leave it out.
var jsonLNav = {itemClassName:"NodeLink",linkClassName:"NodeLinkTitle",linkHideClassName:"HideFromProd",navCategoryClassName:"NavCategory",onLoadJS:"",tree:[{pos:1,wid:"263a97c2-7cb9-470c-bf86-cadc28ae1323",pid:"1",rows:[{hide:0,title:"More IT Help",isNC:0,isMig:0,url:"http://vm-hsspdv-d09p/en-us/Help/Pages/ITHelp.aspx",isOL:0,tree:{pos:2,wid:"263a97c2-7cb9-470c-bf86-cadc28ae1323",pid:"3"}},{hide:0,title:"Office 2010",isNC:0,isMig:1,url:"http://office2010.lmig.com/Pages/Default.aspx",isOL:0,tree:{pos:2,wid:"263a97c2-7cb9-470c-bf86-cadc28ae1323",pid:"9"}},{hide:0,title:"E-mail Management",isNC:0,isMig:0,url:"http://vm-hsspdv-d09p/en-us/Help/EmailManagement/Pages/default.aspx",isOL:0,tree:{pos:2,wid:"8be66348-8da1-4e5c-90c5-0930d2f52d1a",pid:"123"}},]}]};
If you really want to stick with the approach you have, though, I don't think it's really too far off. If I understand what you want, the biggest problem is that you need to do something like:
if(url == cururl )
{
rowNum = rowNum+"x"+x;
return rowNum + " treeDepth:"+tree.pos;
}
Presumably everything that exists in this tree maps to something that exists in the DOM, right? I think the most sensible option would be to stop traversing this object to find what you want, use a library like jQuery with a selector engine to select the node you want, and then use said library to traverse back up the DOM. Even traversing the DOM without a library might be easier for you.