2011-06-05 62 views
12

我有以下結構: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 
      } 
     } 
    } 
} 

終於在視圖:

@using project1.Models 
@model PageMain 

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

有誰知道爲什麼我的模型返回null?我如何訪問PageMain.cs中的數據表?我是MVC的新手,所以如果我在結構中有任何邏輯錯誤,請不要猶豫在警告我:)

+0

這個DataTable對於每次調用都是唯一的,還是像你需要訪問的靜態值? – 2011-06-05 12:14:36

+0

它的內容是根據url參數 – Shaokan 2011-06-05 12:15:35

+0

設計的,該代碼屬於控制器,而不是模型。 – SLaks 2011-06-05 12:24:33

回答

10

首先,您需要設置您的邏輯以從模型到達數據庫。你可以使用ORM來實現這一點。

然後,通過您的模型從您的控制器查看。假設你有一個像下面的人的模型:

public class Person { 

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

} 

爲了查看特定Person數據,您需要查詢您的模型,並從你控制器到您的視圖通過這種模式:

public ActionResult Index() { 

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

    return View(model); 

} 

的上面的控制器正在將人員列表傳遞給您的視圖。 MyDataEntity類是您的實體框架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> 
+0

感謝您的回答! – Shaokan 2011-06-05 13:04:39

5

您需要在控制器中創建一個模型以傳遞給View()

+0

啊,我想,只要我離開返回View()爲空,它就會自動處理它。我想我錯了。謝謝! – Shaokan 2011-06-05 12:14:51

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

是的但仍然,現在我的數據表返回null。我怎樣才能從視圖中使用PageMain.cs中的數據表? – Shaokan 2011-06-05 12:19:10

+0

@Shaokan,需要查看dtable getter代碼才能算出來。 – 2011-06-05 12:23:01

+0

啊,沒關係我已經知道了,實際上我可以得到dtable,但由於代碼錯誤它返回null :)非常感謝! – Shaokan 2011-06-05 12:23:54

0

這發生在我身上,因爲我忘記了我的表單字段的「名稱」屬性。 D'OH!

0

我遇到過同樣的問題。我的錯誤是在模型中擁有同名的屬性。

public class CustomerAddress : BaseEntity 
{ 
    public long CustomerId { get; set; } 


    public string NameSurname { get; set; } 

    public string Region { get; set; } 

    public string City { get; set; } 

    public string Address { get; set; } 

    public string ZipCode { get; set; } 
} 

[HttpPost, ValidateAntiForgeryToken] 
public ActionResult Add(CustomerAddress address){ 

} 

修復方法是替換名稱衝突。

[HttpPost, ValidateAntiForgeryToken] 
public ActionResult Add(CustomerAddress model){ 

} 
相關問題