是否可以在ASP.NET MVC中使用数据源控件?

时间:2021-12-27 15:24:49

I want to use a LinqDataSource or ObjectDataSource with ViewData.Model, where ViewData.Model is an string array.

我想在ViewData.Model中使用LinqDataSource或ObjectDataSource,其中ViewData.Model是一个字符串数组。

I don't want to bind the datasource on view's PageLoad event.

我不想在view的PageLoad事件上绑定数据源。

Is it possible? How?

可能吗?怎么样?

1 个解决方案

#1


1  

You should NOT return the actual datasource into your view since that would break the whole MVC concept. Instead you should return data objects from the source via the controller in order to have a clean separation of the model internals and the view.

您不应该将实际数据源返回到视图中,因为这会破坏整个MVC概念。相反,您应该通过控制器从源返回数据对象,以便清楚地分离模型内部和视图。

However if you really want to return your data source this is how you do it, it is the same way as with any kind of object you want: in your controller you return a new view with the object as a parameter. That object will become available via the view's Model property.

但是,如果您真的想要返回数据源,那么就是这样做的,它与您想要的任何类型的对象相同:在控制器中,您返回一个以对象作为参数的新视图。该对象将通过视图的Model属性提供。

I.e. in your controller action have the following:

即在您的控制器操作中有以下内容:

public ActionResult YourAction() {
    var yourDataSource = GetYourDataSourceMethod();
    return View(yourDataSource);
}

private LinqDataSource GetYourDataSourceMethod() { 
    // Return your datasource ... 
}

In your view you can call the Model property directly and access yourDataSource. You'll need to type cast it if you haven't typed your view like this:

在您的视图中,您可以直接调用Model属性并访问您的DataSource。如果您没有像这样输入视图,则需要输入强制转换:

<%= var myDataSource = (LinqDataSource) Model %>

#1


1  

You should NOT return the actual datasource into your view since that would break the whole MVC concept. Instead you should return data objects from the source via the controller in order to have a clean separation of the model internals and the view.

您不应该将实际数据源返回到视图中,因为这会破坏整个MVC概念。相反,您应该通过控制器从源返回数据对象,以便清楚地分离模型内部和视图。

However if you really want to return your data source this is how you do it, it is the same way as with any kind of object you want: in your controller you return a new view with the object as a parameter. That object will become available via the view's Model property.

但是,如果您真的想要返回数据源,那么就是这样做的,它与您想要的任何类型的对象相同:在控制器中,您返回一个以对象作为参数的新视图。该对象将通过视图的Model属性提供。

I.e. in your controller action have the following:

即在您的控制器操作中有以下内容:

public ActionResult YourAction() {
    var yourDataSource = GetYourDataSourceMethod();
    return View(yourDataSource);
}

private LinqDataSource GetYourDataSourceMethod() { 
    // Return your datasource ... 
}

In your view you can call the Model property directly and access yourDataSource. You'll need to type cast it if you haven't typed your view like this:

在您的视图中,您可以直接调用Model属性并访问您的DataSource。如果您没有像这样输入视图,则需要输入强制转换:

<%= var myDataSource = (LinqDataSource) Model %>