Escaping quotes with JavaScriptSerializer in ASP.NET MVC3
Asked Answered
M

1

9

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?

Mccandless answered 23/4, 2011 at 10:27 Comment(0)
F
25

Use Html.Raw()

Returns markup that is not HTML encoded.

var tags = @Html.Raw(Model.Users);
Freeboard answered 23/4, 2011 at 10:44 Comment(1)
Thank you! I kept seeing odd solutions where people would add a .replace(...) to fix this problem. Thanks for the appropriate one!Gentile

© 2022 - 2024 — McMap. All rights reserved.