user3388473 user3388473 - 3 months ago 30
ASP.NET (C#) Question

How to use dataset values in ASP.NET MVC?

I am taking values(currency rates) from web service in the form of dataset

using Overstock.OverstockCurrency;
using System.Data;


This is my action

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


I have no idea how to use dataset values in my view. So my question is how to use dataset values in view? In what form I should send from controller to view? How to use sent data in view?

UPDATE

I have tried to convert to DataTable and send Datatable to the view

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


In the view, I am taking columns and rows:

@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>


I have run the application. It is giving this compiler error:


CS1061: 'System.Data.DataTable' does not contain a definition for
'Column' and no extension method 'Column' accepting a first argument
of type 'System.Data.DataTable' could be found (are you missing a
using directive or an assembly reference?)


Source error:


Line 13: @foreach (DataColumn col in Model.Column)


To what I should give reference(@using) in order to use Model.Column?

Answer

The idea is to have a model which you can pass to the view.

I don't know what your GetCursOnDate() method returns (I mean what is the form of that data set) but in any case I'm pretty sure you have a known structure of that set.

Knowing this, you have to create a model which maps your DataSet data that you are interested in and then you pass the model to the view as an argument.

If you don't know the result of GetCursOnDate() you can use the debugger to search for the values you are interested in.

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);
}

In view:

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

Or you can have another kind of model like:

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

And then just fill the values from your dataset and pass the model to the view.

In view:

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