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"];
}
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
Modelproperty that represents an instance of the class type specified by your@Modeldeclaration. In your code, you are using the controller class which is not going to work. I rewrote the example to use aDataSetas the model. As you can see, theModelproperty of the View becomes an instance of theSystem.Data.DataSetclass and has all of its properties and methods.View
Controller
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
View
Controller