我的專案中有 4 個模型類。每個模型類都有插入頁面。在我的每個插入資料頁面中,我都會遇到與System.NullReferenceException. 此錯誤顯示在每個@Html.EditorFor屬性中。
假設,我的插入資料頁面(cshtml 頁面)中有 3 個輸入屬性,然后在每個屬性中顯示與System.NullReferenceException. 我不明白為什么會這樣?請看附圖。我無法除錯它,因為錯誤顯示在 cshtml 頁面中。請幫助我為這個錯誤發瘋。
當我在我的方法中實體化模型類并傳遞給查看頁面時,它起作用了。但是現在我很想知道是否這樣,為什么物體框架構建的方法沒有實體化模型類并傳遞給查看頁面。
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UserId,UserName,Password,Department,LocalLvl,Status")] UserModel userModel)
{
if (ModelState.IsValid)
{
db.UserModels.Add(userModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userModel);
}
上面的方法是由Entity Framework腳手架程序創建的,為什么不實體化模型類。之前,我的專案運行成功,然后突然開始顯示錯誤?請幫忙。


uj5u.com熱心網友回復:
預計您已@model在頁面頂部定義該頁面應接收該型別的物件。
@model YourProject.Models.LoginModel
并確保您已回傳模型實體以傳遞給您的視圖。否則,@model將是null。
public ActionResult Login()
{
// Implementation
var model = new LoginModel();
return View(model);
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
// Implementation
return View(model);
}
參考
強型別模型和@model 指令
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420649.html
標籤:
上一篇:將Html.DropDownList的選定值傳遞給控制器
下一篇:更新不同表asp.MVC上的記錄
