tdjfdjdj tdjfdjdj - 3 months ago 30
SQL Question

MVC datasets with viewbags

How do I put a dataset into a viewbag and display the result in a view?

I have a dataset from a model that I write to a viewbag. I want to use a foreach loop to get the datarows out of the viewbag in the view.

I already have a variable going into the view, so I cant pass the dataset normally. I will also have many other datasets per page. so I thought viewbag was the best way to approach this issue.

model

class modeldata
{
public dataset readrows(DataSet dataset)
{
//returns data from sql query.
}
}


controller:

DataSet data = new DataSet();
modeldata getdata = new modeldata ();
ViewBag.Data = getdata.readrows(data);
return view("page1") //based on case statement.
//Already have a value going into view, so I need to use viewbag


View:

@Model site.controllers.homecontroller;

foreach (Model.data row in ViewBag.Data.Rows)
{
@:row["id"] + " " + row["name"];
}

Answer

To display data in the view, you have two options. One is to pass an instance of a Model class to a strongly-typed view. The second option is to use ViewBag. In your case, it looks like you are doing a little bit of both, but I would recommend using the strongly-typed view approach.

The View will have a Model property that represents an instance of the class type specified by your @Model declaration. In your code, you are using the controller class which is not going to work. I rewrote the example to use a DataSet as the model. As you can see, the Model property of the View becomes an instance of the System.Data.DataSet class and has all of its properties and methods.

View

@Model System.Data.DataSet;

foreach (DataRow row in Model.Rows)
{
    @:row["id"] + " " + row["name"];
} 

Controller

DataSet data = new DataSet();
modeldata getdata = new modeldata();
return View(getdata.readrows(data));

Edit:

Here is an example that uses a Dictionary in the model class to store multiple DataSets. You can then modify the View to use the modeldata type as its Model class.

Model

namespace Site.Models
{
    class modeldata
    {
        public Dictionary<string, DataSet> DataSets { get; set; }

        public static DataSet ReadRows(DataSet dataset)
        {
            //returns data from sql query.
        }
    }
}

View

@Model Site.Models.modeldata;

@foreach (System.Data.DataTable table in Model.DataSets["sampleData"].Tables)
{
    foreach (System.Data.DataRow row in table.Rows)
    {
        @:row["id"] + " " + row["name"];
    }
} 

Controller

DataSet data = new DataSet();
modeldata getdata = new modeldata();
getdata.DataSets["sampleData"] = modeldata.ReadRows(data);
return View(getdata);