【问题标题】:Get Data from List to JavaScript MVC 3?从列表中获取数据到 JavaScript MVC 3?
【发布时间】:2013-02-18 14:56:00
【问题描述】:

我正在尝试使用 jq plot 绘制每天汽车租赁的条形图 - x 轴将包含日期,然后包含两个条形 - 已租/未租。我目前将此返回到我的控制器中的列表。如果我设置了一个断点,我可以看到数据被返回,并且列表中的计数为 4(最大值将是 10,因为在我对数据库的 Linq 查询中完成了 Take(10)。

所以我可以将下面作为列表中一行的示例查看

Date         Rented   Not Rented
18/02/2013   100      200

jq 绘图的 javascript 仅在下面带有硬编码值,以查看它是否显示它执行的操作,所以我现在想尝试获取的是 S1 中的值替换为我列表中的每个租用值和值在 s2 中替换为我的未租用,然后将 Ticks 替换为该行的相应日期

//s1 = Rented Values
//s2 = Not Rented Values
var s1 = [200, 600, 700, 1000];
var s2 = [460, 210, 690, 820];
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['Date', 'Date', 'Date', 'Date'];

理想情况下,我在我的 cshtml 页面上寻找类似 Hidden For 的东西,它将包含结果列表并以某种方式在 JS 中访问它?这可能吗?

【问题讨论】:

    标签: c# javascript jquery asp.net-mvc-3 razor


    【解决方案1】:

    一如既往地从定义视图模型开始:

    public class MyViewModel
    {
        public int Rented { get; set; }
        public int NotRented { get; set; }
        public DateTime Date { get; set; }
    }
    

    然后让您的控制器操作查询您的后端并填充此视图模型:

    public ActionResult SomeAction()
    {
        IEnumerable<MyViewModel> model = ... go query your backend
        return View(model);
    }
    

    最后在你的强类型视图中:

    @model IEnumerable<MyViewModel>
    ...
    <script type="text/javascript">
        var s1 = @Html.Raw(Json.Encode(Model.Select(x => x.Rented)));
        var s2 = @Html.Raw(Json.Encode(Model.Select(x => x.NotRented)));
        var ticks = @Html.Raw(Json.Encode(Model.Select(x => x.Date.ToString("dd/MM/yyyy"))));
    
        // Now that you have the 3 arrays plot them up.
    </script>
    

    【讨论】:

    • 或者,如果您想动态加载/更新它 - 在服务器端使用 Controller.Json,在客户端使用 JQuery AJAX 方法之一(加载、获取、发布)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2023-03-15
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多