Passing list from MVC ViewBag to JavaScript

前端 未结 3 1434
执念已碎
执念已碎 2021-02-02 16:57

I have a list of users which I pass from my controller to my view using the view bag. Now I need to be able to pass the same list to the javascript on the page. I could reconstr

3条回答
  •  太阳男子
    2021-02-02 17:52

    You could do that in a single and safe line of code using a JSON parser. You should absolutely never manually build JSON with some string concatenations and stuff as you attempted to do in your example. No need to write any loops as well.

    Here's the correct way to do that:

    
    

    The generated HTML will look exactly as you expect:

    
    

    Of course the next level of improvement in this code is to get rid of the ViewCrap and use a strongly typed view model.

提交回复
热议问题