Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping quotes with JavaScriptSerializer in ASP.NET MVC3

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?

like image 610
MrBliz Avatar asked Apr 23 '11 10:04

MrBliz


1 Answers

Use Html.Raw()

Returns markup that is not HTML encoded.

var tags = @Html.Raw(Model.Users);
like image 51
Mark Coleman Avatar answered Nov 07 '22 00:11

Mark Coleman