Escaping quotes with JavaScriptSerializer in ASP.NET MVC3

MrBliz picture MrBliz · Apr 23, 2011 · Viewed 6.9k times · Source

I Have an Array of users that i want to pass into a view as a javascript array. I'm doing this via JavaScriptSerializer, but the string i get has unescaped quotes in it.

Controller Action

public virtual ActionResult Create(int id) {

        var viewModel = new AttendeeViewModel();

        var data = viewModel.GetMembershipUserList() ;

        viewModel.MeetingID = id;

        viewModel.Users = new JavaScriptSerializer().Serialize(data.ToArray());

        return View(viewModel);
    } 

View

 <script type="text/javascript">

   var tags = @Model.Users

    $(document).ready(function () { $("#mytags").tagit({ availableTags:tags}); });
</script>

ViewModel

 public class AttendeeViewModel
{

    public int AttendeeId { get; set; }
    public string Name { get; set; }
    public int MeetingID { get; set; }
    public string Users { get; set; }

    public List<string> GetMembershipUserList()
    {
        List<string> userNames = new List<string>();
        foreach (MembershipUser user in Membership.GetAllUsers())
        {
            userNames.Add(user.UserName);
        }

        return userNames;

    }
}

This is what Model.Users is output as

[&quot;DennisLeary&quot;,&quot;BobSaget&quot;,&quot;BillHicks&quot;]

How do i escape the quotes with JavaScriptSerializer, or any other method?

Answer

Mark Coleman picture Mark Coleman · Apr 23, 2011

Use Html.Raw()

Returns markup that is not HTML encoded.

var tags = @Html.Raw(Model.Users);