C# – Why is the view model null

asp.net-mvccnull

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:

public class Person {

    public string Name {get;set;}
    public string SurName {get;set;}
    public int Age {get;set;}

}

In order to view specific Person data, you need to query your model and pass this model from you controller to your view:

public ActionResult Index() {

  var _entities = new MyDataEntity();
  var model = _entities.Person;
  model = model.Where(x => x.Age > 20);

  return View(model);

}

The above controller is passing List of Person to your view. MyDataEntity class is your entity framework DataContext class.

After that you need to put @model IEnumerable<Person> inside your model. Here is an example:

@model IEnumerable<MyApp.Models.Person>

<ul>
@foreach(var item in Model){

  <li>Name : @item.Name</li>
  <li>Surname : @item.Surname</li>
  <li>Age : @item.Age</li>

}

</ul>