[英]How to use dataset along with model in ASP.NET Core MVC
@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, ie, @model MyViewModel
like this:我正在使用数据集来检索表数据,但除此之外,我还想使用另一个 model,即@model MyViewModel
,如下所示:
@using System.Data;
@model DataSet
@using WebApplication4.Models;
@model MyViewModel;
I get an error我收到一个错误
Model directive occur only one per document Model 指令每个文档只出现一个
How to put these dataset inside the mode in order to import only MyViewModel
model which consists of dataset data inside it?如何将这些数据集放入模式中以便仅导入其中包含数据集数据的MyViewModel
model?
A view can have only one model.一个视图只能有一个 model。 But that model can be anything you like.但是 model 可以是你喜欢的任何东西。
For example, if you want your model to have a DataSet
property:例如,如果您希望 model 具有DataSet
属性:
public DataSet MyDataSet { get; set; }
Or perhaps you want to create a custom view model composed of both a DataSet
and your model:或者您可能想创建一个自定义视图 model 由DataSet
和您的 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.您可以构建任何您喜欢的 object 从 controller 传递到视图。 So while you can use only a single model instance, that model instance can be composed of whatever you need for the view.因此,虽然您只能使用单个 model 实例,但该 model 实例可以由视图所需的任何内容组成。
you will have to create a special view model class您将必须创建一个特殊视图 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 POST 视图操作
[HttpPost]
public IActionResult PostMyView(ViewModel model)
{
.... your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.