为什么视图模型为空? [英] Why is the view model null?

查看:237
本文介绍了为什么视图模型为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

Controller.cs

Controller.cs

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

PageMain.cs

PageMain.cs

namespace project1.Models
{
    public class PageMain
    {
        public DataTable dtable
        { 
             get {
                       // some code that returns a DataTable
             }
        }
     }
}

最后在视图中:

@using project1.Models
@model PageMain

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

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

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 :)

推荐答案

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

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

}

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

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);

}

以上控制器正在将人员列表"传递给您的视图. MyDataEntity类是您的实体框架DataContext类.

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

之后,您需要将@model IEnumerable<Person>放入模型中.这是一个示例:

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>

这篇关于为什么视图模型为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆