开发者

Why is the view model null?

开发者 https://www.devze.com 2023-03-10 06:32 出处:网络
I have the following structure: Controller.cs public ActionResult PageMain(string param) { return View();

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 err开发者_C百科or in the structure please do not hesitate in warning me :)


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>


You need to create a model in your controller to pass to the View().


public ActionResult PageMain(string param)
{
    return View(new PageMain());
}


This happened to me because I forgot the "name" attribute for my form fields. D'OH!

0

精彩评论

暂无评论...
验证码 换一张
取 消