Storing an Anonymous Object in ViewBag

前端 未结 4 569
Happy的楠姐
Happy的楠姐 2020-12-15 06:14

This is probably a silly question, but I am trying to stuff an anonymous object in ViewBag like so:

ViewBag.Stuff = new { Name = \"Test\", Emai         


        
4条回答
  •  -上瘾入骨i
    2020-12-15 06:21

    we can lovely accomplish that using Json

    Controller : object -> json string , View : Json string -> object

    The scenerio is simply the controller class serialize the C# object into json string then later the view receives this string and deserializes it to an object , like so :

    in Controller :

    using Newtonsoft.Json;
    ViewBag.Stuff = JsonConvert.SerializeObject(new { Name = "Test", Email = "user@domain.com" });
    

    in View :

    @using Newtonsoft.Json
    

    @JsonConvert.DeserializeObject(ViewBag.Stuff).Name

    Note : this was tested in Asp.Net Core 2.2 , Check that link to install Newtonsoft.Json

提交回复
热议问题