为什么视图模型为null?

Sha*_*kan 15 c# asp.net-mvc null

我有以下结构:

Controller.cs

public ActionResult PageMain(string param)
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

PageMain.cs

namespace project1.Models
{
    public class PageMain
    {
        public DataTable dtable
        { 
             get {
                       // some code that returns a DataTable
             }
        }
     }
}
Run Code Online (Sandbox Code Playgroud)

最后在视图中:

@using project1.Models
@model PageMain

var datatable = Model.dtable // but this is throwing an error since the model is null
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么我的模型返回null?如何访问PageMain.cs中的数据表?我是MVC的新手,所以如果我在结构中有任何逻辑错误,请不要犹豫警告我:)

tug*_*erk 13

首先,您需要设置逻辑以从模型到达数据库.您可以使用ORM来实现这一目标.

然后,将模型传递给控制器​​进行查看.假设您的人员模型如下:

public class Person {

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

}
Run Code Online (Sandbox Code Playgroud)

要查看特定Person数据,您需要查询模型并将此模型从您的控制器传递到您的视图:

public ActionResult Index() {

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

  return View(model);

}
Run Code Online (Sandbox Code Playgroud)

上面的控制器将List of Person传递给您的视图.MyDataEntityclass是你的实体框架DataContext类.

之后你需要把@model IEnumerable<Person>你的模型放进去.这是一个例子:

@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>
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 6

您需要在控制器中创建一个模型以传递给View().