How to solve this Javascript/Razor prolem? - c#

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>

Related

Writing Javascript with Razor and Resharper

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>

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

JQuery Autocomplete in MVC3

Sorry I'm very new to JQuery... I can't for the life of me figure out where my bug is. When I run this I don't get any results. When I check the error in Firefox and Chrome it points to the source line. I just can't see anything wrong.
Here's my script
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#CustName').autocomplete({
//Firefox points to a syntax error here
source: #SqlHelper.getJSONArray("CustName", "dba.BillingInfo")
});
});
</script>
<p>Customer Name #Html.TextBox("CustName")</p>
SqlHelper.getJsonArray is a method I'm using to return a JSON string. I've checked and double checked that it is in fact returning valid JSON.
public static string getJSONArray(string column,string table)
{
string qry = "SELECT DISTINCT " + column
+ " FROM " + table
+ " WHERE " + column + " is not null"
+ " AND " + column + " <> ''"
+ " ORDER BY 1";
List<string> result = new List<string>();
SqlDataReader reader = execQry(qry);
while (reader.Read())
{
result.Add(reader[0].ToString());
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(result);
}
[UPDATE]
Here is the syntax error firefox is spitting back:
source: $.parseJSON(["Customer1","Customer2...
---------------------^
So I'm beginning to think the issue is the quotes are getting rendered as quot; instead of ". If I try putting my source as ["Test1","Test2","Test3"] it works fine. Is there a way to get razor to not HTML encode the string?
[UPDATE]
That was the issue. The solution was using Html.Raw()
The issue was razor automatically HTML encoding the JSON. The fix is using HTML.Raw
$('#CustName').autocomplete({
source: #Html.Raw(SqlHelper.getJSONArray("CustName", "dba.BillingInfo"))
});
Try using $.parseJSON.
$(document).ready(function () {
$('#CustName').autocomplete({
//Firefox points to a syntax error here
source: $.parseJSON(#SqlHelper.getJSONArray("CustName", "dba.BillingInfo"))
});
});

Categories