c# - 为什么 View 模型为空?

标签 c# asp.net-mvc null

我有以下结构:

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
             }
        }
     }
}

最后在 View 中:

@using project1.Models
@model PageMain

var datatable = Model.dtable // but this is throwing an error since the model is null

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

最佳答案

首先,您需要设置逻辑以从您的模型访问数据库。您可以使用 ORM 来实现这一点。

然后,将您的模型传递给 Controller ​​查看。假设您的人物模型如下:

public class Person {

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

}

为了查看具体Person数据,你需要查询你的模型并将这个模型从你的 Controller 传递到你的 View :

public ActionResult Index() {

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

  return View(model);

}

上面的 Controller 正在将人员列表传递给您的 View 。 MyDataEntity类是你的 Entity Framework 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>

关于c# - 为什么 View 模型为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6242810/

相关文章:

c++ - 在成员函数中测试 this 指针是否合法 C++?

c# - 具有标志属性的枚举

c# - 从WCF应用程序传递回WPF应用程序的ReportServer的byte []反序列化上没有BinaryHeader错误

c# - ASP MVC - 使用时区和文化处理日期时间本地化

c# - 在 mVC4 中更改按钮文本而不刷新页面

javascript - 检查空跨浏览器的完整方法是什么

MySQL 显示值为 NULL 或等于 X 的行

c# - 以编程方式安装证书吊销列表 C#

c# - 我怎样才能使我的类变量只能设置为三个选项之一?

asp.net - 使用 RenderPartialToString 时显示模型状态错误的问题