Home > Back-end >  How to use dataset along with model in ASP.NET Core MVC
How to use dataset along with model in ASP.NET Core MVC

Time:12-30

@using System.Data;    
@model DataSet;     
@using WebApplication4.Models; 

I am using a dataset to retrieve table data, but in addition to that I also want to use another model, i.e., @model MyViewModel like this:

@using System.Data;
@model DataSet
@using WebApplication4.Models;
@model MyViewModel;

I get an error

Model directive occur only one per document

How to put these dataset inside the mode in order to import only MyViewModel model which consists of dataset data inside it?

CodePudding user response:

A view can have only one model. But that model can be anything you like.

For example, if you want your model to have a DataSet property:

public DataSet MyDataSet { get; set; }

Or perhaps you want to create a custom view model composed of both a DataSet and your model:

public class MyCompositeViewModel
{
    public DataSet MyDataSet { get; set; }
    public MyViewModel ViewModel { get; set; }
}

You can construct any object you like to pass from the controller to the view. So while you can use only a single model instance, that model instance can be composed of whatever you need for the view.

CodePudding user response:

you will have to create a special view model class

public class ViewModel
{
    public DataSet MyDataSet { get; set; }
    public MyAnotherModel MyAnotherModel { get; set; }
}

GET view action

[HttpGet]
public IActionResult GetMyView()
{
    var  dataSet = ... your code
    myAnotherModel = ... your coe

    var model= new ViewModel
    {
     MyDataSet =dataSet;
     MyAnotherModel =myAnotherModel
      }

return View (model);
}

GET view

@model ViewModel
....

POST view action

[HttpPost]
public IActionResult PostMyView(ViewModel model)
{
    .... your code
}
  • Related