【问题标题】:How to use dataset values in ASP.NET MVC?如何在 ASP.NET MVC 中使用数据集值?
【发布时间】:2014-03-15 20:07:25
【问题描述】:

我以数据集的形式从web service 获取值(汇率)

using Overstock.OverstockCurrency;
using System.Data;

这是我的行动

public ActionResult CurrencyConvertor()
    {
        DataSet ds = new DailyInfoSoapClient().GetCursOnDate(DateTime.Today);
        return View(ds);
    }

我不知道如何在我的视图中使用数据集值。所以我的问题是如何在视图中使用数据集值?我应该以什么形式从控制器发送到视图?如何在视图中使用发送的数据?

更新

我已尝试转换为 DataTable 并将 Datatable 发送到视图

public ActionResult CurrencyConvertor()
        {
            DataSet ds = new DailyInfoSoapClient().GetCursOnDate(DateTime.Today);
            DataTable Table = ds.Tables[0];
            return View(Table);
        }

在视图中,我正在取列和行:

    @model System.Data.DataTable
@using System.Data

@{
    ViewBag.Title = "CurrencyConvertor";
}

<h2>CurrencyConvertor</h2>

<table> 
    <thead> 
    <tr> 
    @foreach (DataColumn col in Model.Column)     
    {          
        <th>@col.ColumnName</th> 
    }     
    </tr> 
    </thead>         
    <tbody> 
    @foreach (DataRow row in Model.Rows)     
    {         
        <tr> 
        @foreach (DataColumn col in Model.Columns)         
        {              
            <td>@row[col.ColumnName]</td> 
        }         
        </tr> 
    }     
    </tbody> 
</table>

我已经运行了应用程序。它给出了这个编译器错误:

CS1061:“System.Data.DataTable”不包含对 'Column' 并且没有扩展方法 'Column' 接受第一个参数 可以找到“System.Data.DataTable”类型的(您是否缺少 使用指令还是程序集引用?)

来源错误:

第 13 行:@foreach(Model.Column 中的 DataColumn col)

为了使用 Model.Column,我应该提供什么参考(@using)?

【问题讨论】:

标签: asp.net asp.net-mvc web-services asp.net-mvc-4 dataset


【解决方案1】:

我们的想法是有一个可以传递给视图的模型。

我不知道您的 GetCursOnDate() 方法返回什么(我的意思是该数据集的形式是什么),但无论如何我很确定您有该数据集的已知结构。

了解这一点后,您必须创建一个模型来映射您感兴趣的 DataSet 数据,然后将该模型作为参数传递给视图。

如果您不知道GetCursOnDate() 的结果,您可以使用调试器搜索您感兴趣的值。

public ActionResult CurrencyConvertor()
{
    DataSet ds = new DailyInfoSoapClient().GetCursOnDate(DateTime.Today);
    Dictionary<string, decimal> model = new Dictionary<string, decimal>();
    model.Add("eur", dataset_value_for_eur);
    return View(model);
}

在视图中:

@model Dictionary<string,decimal> // put this in the first line of your view

或者你可以有另一种模型,比如:

public class CurrencyViewModel {
    public decimal EUR {get;set;}
    public decimal USD {get;set;}
}

然后只需从数据集中填充值并将模型传递给视图。

在视图中:

@model the_namespace.CurrencyViewModel // put this in the first line of your view

【讨论】:

  • Tnx,我将尝试确定 GetCursOnDate() 返回的内容。
猜你喜欢
  • 2022-01-27
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多