Let's say I have following ASP.NET Web Form engine code, how can I express it in Razor engine?
<script type="text/javascript">
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
</script>
Thanks
Hardy
I would use the following:
<script type="text/javascript">
var initialData = #Html.Raw(new JavaScriptSerializer().Serialize(Model));
</script>
This is exactly the same as your example (note the Html.Raw).
If you want the output (html)encoded or your code returns an IHtmlString :
<script type="text/javascript">
var initialData = #(new JavaScriptSerializer().Serialize(Model));
</script>
You do want to use #( ... ) syntax, because using #new JavaScriptSerializer(..) will let the Razor parser stop at the first space (after new).
The syntax like this:
<script type="text/javascript">
var initialData = #{ new JavaScriptSerializer().Serialize(Model); }; #* <== wrong *#
</script>
does not work because it will call new JavaScriptSerializer, but discard the output.
Related
I have created a razor view (Demo.cshtml) and I tried to declare razor variable within javascript block as shown below:
Code:
#{
ViewBag.Title = "Demo";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Demo</h2>
<script type="text/javascript">
$(function () {
#{
bool test = true;
}
});
</script>
I am getting few warnings as mentioned below:
Warning 1 Invalid character Demo.cshtml 10 10
Warning 2 Expected ';' Demo.cshtml 11 18
Can anyone guide me in resolving the above warning?
Well its not so easy to explain. For different needs you can use different solutions.
The easiest way is to use 'text' tag:
<script type="text/javascript">
#{
<text>
alert(#myVar);
</text>
}
</script>
And for example for String values you can do like
<script type="text/javascript">
var url = '#Url.RouteUrl("admin", new { controller = "users"})';
</script>
For boolean types you can do like in this example, but it looks like a stupid hack :)
var bool = '#ViewData.ModelState.IsValid' == "True";
And for collections you need to implement some helper method to be able to call
var myArray = #Html.ToJson(MyCSharpCollectionObject)
Im trying to insert a simple handlebars, like this, but there's so little support and the guide in the official page is so sad that I couldnt accomplish this.
<head>
<!--HANDLEBAR-->
<script type="text/x-handlebars" data-template-name="say-hello">
Hello, <b>{{name}}</b>
</script>
<!--VIEW-->
<script>
var view = Ember.View.create({
templateName: 'say-hello',
name: "Bob",
});
view.appendTo('#templateHere'); //here I try to append the view
</script>
In firebug I get the error: unable to find the template "say-hello"...........but I dont know why doesnt find it
Finally I accomplished, I write the solutions here because I think that ember need more documentation and it's worth because is very interesting (and powerful):
The problem was that I create an object of my view before defining it. The right code is this:
....
<!--HANDLEBAR-->
<script type="text/x-handlebars" data-template-name="say-hello">
Hello, <b>{{name}}</b>
</script>
<!--VIEW-->
<script>
App = Ember.Application.create();
//DEFINE VIEW
App.Myview = Ember.View.extend({
templateName: 'say-hello',
name: "Bob",
});
//CREATE VIEW>
App.myview=App.Myview.create();
console.log(App.myview.get('name'));//only for debug
//APPEND VIEW
$(function() {
App.myview.append('#templateHere');
});
</script>
</head>
<body>
<div id="templateHere"></div>
</body>
</html>
I started to learn MVC and in conjunction want to use the KnockOut.js
I am having trouble understanding why the new # include tag encodes everything to HTML(edit: ok i know now to prevent XSS).. but even worse how to stop it from doing that..
I have this code.
#{
ViewBag.Title = "Home Page";
var myData = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
<script type="text/javascript">
var initialData = #myData ;
Which produces this source
<script type="text/javascript">
var initialData = [{"Title":"Tall Hat","Price":49.95},{"Title":"Long Cloak","Price":78.25}] ;
Ok. so tried using HttpUtility.HtmlDecode.. and nothing happens on the included bit in the javascript because the razor engine is reencoding it? but if it use the encode then reecnodes the encodes html.. briallinat.
I cannot work out how to stop the encoding.
The msdn says use #: but that does not work in the javascript block, i even tried
#{ #:new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);}
That just something wierd and causes other errors.
How should this be done in the MVC model?
In aspx using
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
works fine..
Html.Raw(string) will write out your string in its raw, unencoded form. Provided your string is not encoded to begin with.
code example as requested (?!?!)
#{
ViewBag.Title = "Home Page";
var myData = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
<script type="text/javascript">
var initialData = #Html.Raw(myData) ;
MVC (or the Razor view engine in this case) encodes all your strings as a HTML string using the MvcHtmlString by default. To get around it, use:
<script type="text/javascript">
var initialData = "#MvcHtmlString.Create(myData)";
</script>
This then assumes your string has already been encoded.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=true"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var input = document.getElementById('location');
var options = {
types: ["locality"]
};
autocomplete = new google.maps.places.Autocomplete(input, options);
});
</script>
</head>
<body>
<div>Location: <input type="text" id="location" style="width:400px;" /></div>
</body>
</html>
There is my code to generate my autocomplete location text input. Google's list of supported types (http://code.google.com/apis/maps/documentation/places/supported_types.html) shows "locality" as being the type to use when I do not wish for everything to come back in the result(businesses, etc). I am getting no results.
Basically, what I would like to achieve is to search for a city (IE: Toronto) And only see results like: "Toronto, ON, Canada". Perhaps I am confused on how I implement this API.
Thank you very much for your replies!
I think the option you are looking for according to the docs is "geocode" ( http://code.google.com/apis/maps/documentation/javascript/reference.html#AutocompleteOptions ):
var options = {
types: ["geocode"]
};
you can also use the country restriction
example:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: "ca"}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input id="searchTextField" type="text" size="50" placeholder="Anything you want!">
now you can easily add a dropdown with a selection of cities and re-filter the cities, when onchange of the dropdown occurs :)
Try, check out the jsfiddle:
var options = {
types: ['geocode']
};
types, which can be either establishment or geocode, representing
businesses or addresses, respectively. If types is not specified, both
types are returned.
If the user types Tor in the input field and the output you want is Toronto, ON, Canada then you should use types=(regions), with the brackets.
I don't know if the option was present when the question was asked, but it is available now.
Sample Request:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Tor&key=<YOUR_API_KEY_HERE>&types=(regions)
You can use like this
types: ['geocode' || 'establishment' || 'address']
I'm trying to implement this Knockout example using ASP MVC 3's "Razor" view engine.
The first topic covers simple data binding of a C# array using the standard ASP view engine. I am trying the sample example using "Razor", and this line:
<script type="text/javascript">
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
</script>
results in an empty variable for initialData.
I also tried this:
#{
string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
And then specified the initialData like this:
var initialData = #Html.Raw(data);
This populates initialData with the dataset, but binding does not work.
I'm just trying to databind this set in order to display a count of the ideas, as in the example:
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
Why isn't data binding working in this instance?
The easiest way in MVC3 is to do:
var initialData = #Html.Raw(Json.Encode(Model));
I ran into this same problem, and discovered that it was my own stupidity that caused the issue (which it so often is). I forgot to wait until the DOM loaded to call ko.applyBindings(viewModel) - so simply using:
$(document).ready(function () { ko.applyBindings(viewModel); });
So the whole script as
<script type="text/javascript">
var initialData = #Html.Raw( new JavaScriptSerializer().Serialize(Model));
var viewModel = {
gifts: ko.observableArray(initialData)
};
$(document).ready(function () { ko.applyBindings(viewModel); });
</script>
This worked with knockout-1.2.1.js and jquery-1.5.1.js