I have the following code in my controller:
public ActionResult MyPage()
{
var vm = new MyViewModel();
vm.StringList = "'" + String.Join("','", MyModel.GetList().Select(r => r.Name).ToArray()) + "'";
return View(vm);
}
and in my asp.net-mvc view i have the following code:
var myJavascriptArray = [<%=Model.StringList %>];
inside a javascript function
this works fine until one of the names in the:
MyModel.GetList()
call has a apostrophe in it like “Bill O’Brien”
as that messes up my javascript code as it thinks the ‘ after the O is the end of that entry and the line breaks.
What is the best way to escape out of this character so i can have an array in javascript like that will ultimately show up as this:
var myJavascriptArray = [”Item 1′,Item 2′,’Item 3′,’Item 4′];
and deal with ‘Bill O’Brien’ being one of the entries.
Are you trying to do some sort of JSON serialization with all those manual apostrophes and stuff? Don’t.
Simply define a view model that will contain a list of names:
that you will populate in your controller and pass to the view:
and in the view JSON serialize this property:
Or if you are using ASP.NET MVC 3:
which will result in a correctly JSON encoded array of strings in the view:
which you can manipulate as a normal js array:
Obviously this technique works with more complex object graphs than simple array of strings. You could safe serialize entire object models without worrying about single, double quotes, parenthesis, etc … Of course in addition to all this the javascript serializer will deal with names like
Bill O'Brienand properly encode them.