问题描述:

I have an MVC program that is uploading data from a .csv file to a SQL database. I am now trying to display the data uploaded with a WebGrid table. All the examples that I have seen demonstrate only displaying one complete table at a time.

I am new to using MVC and WebGrid, so first of all I was wondering if this was the right approach to this problem, and secondly, if this approach is the best route, how will I have to set up the Views to display data from 3 different tables. Will it require 3 different controllers & 3 different views, and will I have to have multiple Data Models? Any input would be really appreciated.

网友答案:

Here are some MVC best practices:

Your view model should be what you want to display on the view
This seems obvious, but at first it is not. Start by creating your view model, and when you're doing that assume that you know nothing about your data store.

Your view model should not know/care how your data is stored
The view's job is just to display some data, that is all. Your view model should be something like this:

public class ViewModel123 {
   public int ID {get;set;}
   public string foo {get;set;}//this may come from table A or table B, it does not matter
   public string bar {get;set;}//this may come from table A or table B, it does not matter
}

Create a data access layer

This is the layer that gets data out of the database from N number of tables. Assuming you're using EF or linq-to-sql the method to get the data would look something like this:

public IEnumerable<ViewModel123> GetData() {
   return DatabaseHande.SomeThing.Select(x=> new ViewModel123 {
   ID = x.id,
   Foo = x.Foo,
   Bar = x.LinkTable.Bar
});
}

Have your controller call your data access layer and return the view model

You controller can now call the data access layer and return the view model to the view. More pseudo code:

public ActionResult List() {
   var viewModelDataRows = _dataAccessClass.GetData();
   return View(viewModelDataRows);
}
相关阅读:
Top