传递从名单MVC ViewBag为JavaScript [英] Passing list from MVC ViewBag to JavaScript

查看:429
本文介绍了传递从名单MVC ViewBag为JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我从我的控制器传递到使用视图袋我的观点的用户列表。现在我需要能够在同一个列表传递到页面上的JavaScript。我可以使用foreach循环重建列表:

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 reconstruct the list using a foreach loop:

    @foreach (var item in ViewBag.userList) //Gets list of users passed from controller and adds markers to the map
{
    var userLat = item.LastLatitude;
    var userLon = item.LastLongitude;
    var _userId = item.Id;

    <script>array.push({"userId":"'@_userId'","userLat":"'@userLat'","userLon":"'@userLon'"});</script>
}

然而,这似乎是一个混乱的方法,并需要大量的返工的,如果更改。我知道有关于堆栈溢出类似的职位,但他们中的很多使用MVC的previous版本相同的语法似乎并不适用。任何想法?

However this seems like a messy approach and required a lot of reworking if a change is made. I know there are similar posts on Stack overflow, but a lot of them use previous version of MVC and the same syntax doesn't seem to apply. Any ideas?

推荐答案

您可以做,在code单一,安全线使用JSON解析器。您应该绝对不会手动一些字符串连接之类的东西打造JSON作为您试图在你的例子做。无需编写任何循环为好。

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:

<script type="text/javascript">
    var array = @Html.Raw(
        Json.Encode(
            ((IEnumerable<UserModel>)ViewBag.userList).Select(user => new 
            { 
                userId = user.Id, 
                userLat = user.LastLatitude, 
                userLon = user.LastLongitude 
            })
        )
    );

    alert(array[0].userId);
</script>

生成的HTML将看起来完全像您期望的:

The generated HTML will look exactly as you expect:

<script type="text/javascript">
    var array = [{"userId":1,"userLat":10,"userLon":15}, {"userId":2,"userLat":20,"userLon":30}, ...];
    alert(array[0].userId);
</script>

当然在这个code提高一个层次是摆脱的 ViewCrap ,并使用强类型的视图模型。

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

这篇关于传递从名单MVC ViewBag为JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆