在 ASP.NET MVC3 中使用 JavaScriptSerializer 转义引号
我有一个用户数组,我想将其作为 javascript 数组传递到视图中。我通过 JavaScriptSerializer 执行此操作,但我得到的字符串中包含未转义的引号。
控制器操作
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);
}
查看
<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;
}
}
这就是 Model.Users 的输出:
["DennisLeary","BobSaget","BillHicks"]
如何使用 JavaScriptSerializer 或任何其他方法转义引号?
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
["DennisLeary","BobSaget","BillHicks"]
How do i escape the quotes with JavaScriptSerializer, or any other method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Html.Raw()
Use
Html.Raw()