简体   繁体   中英

how to escape an apostrophe in asp.net-mvc and javascript

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:

public class MyViewModel
{
    public string[] Names { get; set; }
} 

that you will populate in your controller and pass to the view:

public ActionResult MyPage()
{
    var model = new MyViewModel
    {
        Names = MyModel.GetList().Select(r => r.Name).ToArray()
    }
    return View(model);
}

and in the view JSON serialize this property:

var myJavascriptArray = <%= new JavaScriptSerializer().Serialize(Model.Names) %>;

Or if you are using ASP.NET MVC 3:

var myJavascriptArray = <%= Json.Encode(Model.Names) %>;

which will result in a correctly JSON encoded array of strings in the view:

var myJavascriptArray = ["name 1", "name 2", "name 3"];

which you can manipulate as a normal js array:

alert(myJavascriptArray[1]);

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'Brien and properly encode them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM