I have the following structure:
Controller.cs
public ActionResult PageMain(string param)
{
return View();
}
PageMain.cs
namespace project1.Models
{
public class PageMain
{
public DataTable dtable
{
get {
// some code that returns a DataTable
}
}
}
}
and finally in the view:
@using project1.Models
@model PageMain
var datatable = Model.dtable // but this is throwing an error since the model is null
Does anyone know why my model is returning null? How can I access the datatable in the PageMain.cs? I am new to MVC so if I have any logical error in the structure please do not hesitate in warning me 🙂
Best Answer
First, you need to set your logic to reach the database form your model. You could use ORM to achieve that.
Then, pass your model to view from your controller. Assume that you have your person model like below:
In order to view specific
Person
data, you need to query your model and pass this model from you controller to your view:The above controller is passing List of Person to your view.
MyDataEntity
class is your entity frameworkDataContext
class.After that you need to put
@model IEnumerable<Person>
inside your model. Here is an example: