Writing Javascript with Razor and Resharper - c#

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>

Related

How to solve this Javascript/Razor prolem?

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>

asp.net mvc 4 javascript inside razor block throws error

This is my razor code which throws error:
#section script
{
<script type="text/javascript">
$(document).ready(function () {
#if (TempData["Message"] != null)
{
showNotification("'" + TempData["Message"].ToString() + "'");
}
});
</script>
}
It says showNotification doesn't exist. It thinks this is a C# code where it's a javascript function. Could anybody please let me know how do I fix this error? Thanks!
Throw a text tag around it, since the compiler thinks your JavaScript is Razor syntax. When you do this, you will need to add a # to the TempData call.
#section script
{
<script type="text/javascript">
$(document).ready(function () {
#if (TempData["Message"] != null)
{
<text>showNotification('#TempData["Message"].ToString()');</text>
}
});
</script>
}
In addition to #Martin's answer, you can also put #: in front of the showNotification call. The #: syntax tells Razor to treat that single line as HTML, where the tells Razor to treat anything within the text tag as HTML (useful for multi line, where #: is good for single line).

How to get label value which loads with javascript

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.

How do I access ViewBag from JS

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();

Access ViewData Using JQuery

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>

Categories