【问题标题】:How can I pass the results returned by a method from controller to the view如何将方法返回的结果从控制器传递到视图
【发布时间】:2016-04-13 00:22:33
【问题描述】:

我想在我的视图中使用控制器的方法(在我的例子中是光标)返回的结果, 为了从返回的数据中绘制图表。 我写了一段代码,但我还没有找到如何将数据传递给视图。

   //controller
    [HttpPost]
    public async System.Threading.Tasks.Task<ActionResult> drawgraph(Inputmodel m)
    {
        List<Client> client = new List<Client>();
        var collection = db.GetCollection<Client>("Client");
        var builder = Builders<Client>.Filter;
        var beginDate = Convert.ToDateTime(m.date_begin).Date;
        var endDate = Convert.ToDateTime(m.date_end).Date;
        var filter = builder.Gte("date", beginDate) & builder.Lt("date", endDate.AddDays(1)) & builder.Eq("field2", m.taux);
        var cursor = await collection.DistinctAsync<double>("field2",filter);      
        return View(cursor);


    }

//view
 @{
   var myChart = new Chart(width:600,height: 400)
                .AddTitle("graphique")
                .AddSeries(chartType: "Line")
                .DataBindTable(dataSource: cursor, xField: "date", yField:"field2") //here I want to use the returnet result by drawgraph in the controller
                 .Write();
  }

【问题讨论】:

  • 您需要创建一个模型,将数据传递给它,然后在您的视图中使用该模型。

标签: c# asp.net-mvc linechart


【解决方案1】:

您必须强烈键入您的视图才能访问模型:

 @model YourModelTypeHere @*type of the cursor variable*@
 //view
 @{
     var myChart = new Chart(width:600,height: 400)
                       .AddTitle("graphique")
                       .AddSeries(chartType: "Line")
                       .DataBindTable(dataSource: Model, xField: "date", yField:"field2") //here I want to use the returnet result by drawgraph in the controller
                       .Write();
 }

然后你可以使用 web 视图页面的 Model 属性来获取你的模型。

请看这个article

【讨论】:

    【解决方案2】:

    你可以使用

    在控制器中

    ViewBag.MyData = cursor;
    

    //在视图中:

    @ViewBag.MyData
    

    从控制器访问数据。

    但最佳做法是使用强类型视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多