Search code examples
javascriptjsonasp.net-mvc-4unicodejavascriptserializer

asp.net MVC display encoding character


In my project, I serialize an object by JavaScriptSerializer. Then, I want to display in my cshtml page. Unfortunately, the result is not what I want.

My controller is very simple:

public class HomeController : Controller
    {

        public ActionResult Index()
        {
            var person = new Person
            {
                Name = "yubaolee <yubaolee>",
            };

            return View((object) new JavaScriptSerializer().Serialize(person));
        }
    }

    public class Person
    {
        public string Name;
    }

I try some methods like:

@Model
<br />
js document.write:
<script>
    document.write('@Model');
</script>

the output is:

enter image description here

Two results are not what I want. I want to get:

{"Name":"yubaolee <yubaolee>"} 

Solution

  • You could use the Newtonsoft.Json NuGet package which contains the static class JsonConvert that you can use in your controller this way:

    object json = JsonConvert.SerializeObject(person); return View(json);