I’ve just started to work with ASP.NET MVC projects, I have gotten past the basics, but I came across with a problem recently, I can’t pass a string as a id from a View.
So far, I’ve been passing the id to a javascript function like this:
<script>app.init( <%: ViewContext.RouteData.Values["id"].ToString() %>)</script>
This calls the following javascript function:
var app = {};
(function (app) {
var _id;
app.init = function (id) {
_id = id;
}
app.id = function () {
return _id;
}
})(app);
I’m doing this because I need to work with the id to perform operations like submits and ajax calls in javascript (I prefer working with javascript).
So far this has worked with int values, but when I tried to pass a string it fails. For example if I try to access to this url localhost:65097/Device/Edit/D2C02 it shows the following error:
SCRIPT5009: 'D2C02' is undefined
When I check the generated html code, the call to the function looked like this:
<script>app.init(D2C02)</script>
Shouldn’t the id be passed as ‘D2C02’ like a string, instead of just D2C02 like a variable? Because that’s what I’m understading the browser thinks the id D2C02 represents. How can I make sure the id value is passed on to the javascript function as a string?
ToString()just converts something to a string – but that’s a C# string, not a JS string. So the easiest solution is to add quotes assuming the value can never contain quotes, too:If it may contain quotes you can either perform a simple replacement to backslash-escape them or run the string through a JSON serializer that takes care of turning it into a valid JavaScript string.