My attempted methods.
Looking at the JS via browser, the #ViewBag.CC is just blank... (missing)
var c = "#" + "#ViewBag.CC";
var d = $("#" + "#ViewBag.CC").value;
var e = $("#" + "#ViewBag.CC").val();
var c = "#ViewBag.CC";
var d = $("#ViewBag.CC").value;
var e = $("#ViewBag.CC").val();
if you are using razor engine template then do the following
in your view write :
<script> var myJsVariable = '#ViewBag.MyVariable' </script>
UPDATE:
A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
<head>
<script>
var AppConfig = #Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
try: var cc = #Html.Raw(Json.Encode(ViewBag.CC)
<script type="text/javascript">
$(document).ready(function() {
showWarning('#ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
ViewBag is server side code.
Javascript is client side code.
You can't really connect them.
You can do something like this:
var x = $('#' + '#(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("#(ViewBag.CC)").value;
or if you want to use jQuery, then:
jQuery
var myValue = $('#' + '#(ViewBag.CC)').val();
None of the existing solutions worked for me. Here's another solution I found that did work:
Controller:
TempData["SuccessMessage"] = "your message here";
View:
let msg = '#TempData["SuccessMessage"]';
Try this:
Anywhere in HTML: <input hidden value=#ViewBag.CC id="CC_id" />
In JS: var CC= document.getElementById("CC_id").value.toString();
Related
I've just gotten a Google Analytics project, the first I've ever worked on, and what I want to do is simple. I need to add a line between the 'create' and 'send' portions of the script code that reads ga('require','displayfeatures'). It seems simple but this is the code I have to work with and I have no idea how to edit it:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-3724234-5");
//this is where I need to ad the ga('require','displayfeatures') area
pageTracker._trackPageview();
} catch (err) { }
</script>
I've been able to find some info about ga('something','something') but that is not what is being currently used in the JavaScript above.
Note: None of the code is mind--all of it was created by another programmer who is not available to answer questions about his code.
Any suggestons? I really want to try and get this done quickly--I feel it shouldn't be taking this long!
The google analytics code you have, is the old version, where no ga 'stuff' is used, it looks like this:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Whereas the new analytics code looks like this:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'mydomain.com');
ga('send', 'pageview');
</script>
As you can see, at the end there are the ga statements where you can add yours.
I would recommend upgrading the code, you just have to know and exchange your tracking ID (UA-XXXXXXXX-X).
Read more about it here: Google analytics devguides
I am trying to write the following javascript in Razor (MVC4).
(The Script tags are there)
var isPaid = true;
in the view I use the Model to get the value:
var isPaid = #Model.Paid;
<text>
var proceed = #Model.Paid;
</text>
var proceed = #Html.Raw(Model.Paid + ";")
Most of the time Resharper complains
You could try it this way:
<script type="text/javascript">
var isPaid = false; // This is JavaScript.
// The if statement is C#, hence the #.
#if (Model.Paid)
{
#:isPaid = true; // Set the JS variable to true.
}
// Below is JavaScript code again.
alert(isPaid);
</script>
Text after the #: nugget will be interpreted as as JavaScript. It is a bit of a hassle for booleans, a string property for example is a lot easier:
<script type="text/javascript">
var userName = '#Model.UserName';
</script>
You can't combine JavaScript inside HTML code and you need to put quotes & angle-brackets around the value so that it is considered as a string.
The problem seems to be this and more..:
var isPaid = #Model.Paid;
<text>
var proceed = #Model.Paid;
</text>
A proposed solution would be:
Normal JavaScript code should resides within a script tag, for example:
<script type="text/javascript">
var isPaid = '<%: #Model.Paid %>';
</script>
I try to add the following javascript code.
<script>
#if (ViewBag.checkedArtikel != null)
{
foreach (int ac in ViewBag.checkedArtikel)
{
String temp = "'#addartikel" + ac + "'";
<text> $(#temp).toggleClass('down');</text>
}
}
</script>
If i leave out the script tag i get the right jquery commands:
$('#addartikel1').toggleClass('down');
But with the script tag i get this error:
Uncaught SyntaxError: Unexpected token &
You have very badly mixed server side Razor code with client side javascript. Here's the correct way to do that, by using a JSON serializer:
<script type="text/javascript">
var articles = #Html.Raw(Json.Encode(ViewBag.checkedArtikel ?? new int[0]));
$(articles).each(function() {
$('#addartikel' + this).toggleClass('down');
});
</script>
Use this code:
<text>$(#Html.Raw(temp)).toggleClass('down');</text>
Or you can use your old code without adding quotes to variable:
String temp = "#addartikel" + ac;
<text> $('#temp').toggleClass('down');</text>
I have a link like that. It's getting from instagram api.
http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b
How can I get this link from codebehind?
I can take it with js but i can't get it after assign to label. I mean:
<script>
function getURL(){
document.getElementById('lblAccessToken').innerText = location.href;
}
</script>
This js function is in body onload event. How can I reach this innerText value from codebehind?
If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this
Markup
<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token");
$("#lblAccessToken").html( myToken );
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things
Pass the hash value to a jQuery ajax method and store it there.
Grab the hash value and redirect to the same page after converting it to a querystring
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token") || "";
if(my_token !=== ""){
window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
}
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Now at Page_Load, grab it like
string token = Request.QueryString["access_token"];
Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.
I am developing a mvc application.I wrote a jquery for different operations and saved in to a js file named my.js. And i included that js file into my page.
<script src="../../Scripts/my.js" type="text/javascript"></script>
How can i access ViewData from that js file. I tried many methods.But didnt worked yet.
The code i used to access ViewData from js file is shown below.
var CalanderPreference = "<%= ViewData["CalanderPreference"] %>";
But it returning an error like 'Expected ; '
Any ideas?
ViewData is not accessible on client, because it exists only on view rendering.
You could serialize your view data to json on server side, write it to hidden field, and them parse it to javascript object on client side.
You can create your javascript object on the view like in this example.
Put this into your view and not in a seperate file:
<script type="text/javascript">
$(function() {
var saleYear = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Year %>");
var saleMonth = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Month %>") - 1;
var saleDay = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Day %>");
var saleHour = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Hour %>");
var saleMinute = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Minute %>");
var saleSecond = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Second %>");
var endSaleDate = new Date(saleYear, saleMonth, saleDay, saleHour, saleMinute, saleSecond);
$("#countDownSale24").countdown({ until: endSaleDate, compact: true, format: "HMS" });
});
</script>