我有以下结构:
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/