![](/img/trans.png)
[英]Why Is My ASP.NET MVC Model Filled in the Controller, but Null in the View?
[英]Why does this value in my model return null when used in my controller? (ASP.NET MVC)
在我的 model 中,我有一個名為 itemCheck 的布爾值:
public class Item
{
public Array userDataItems { get; set; }
public char[] delimiterChar { get; set; }
public bool itemCheck { get; set; }
}
我的 viewModel,將項目 model 鏈接到 controller:
public class CategoryItemViewModel
{
public Item ItemList { get; set; }
public Category CategoryList { get; set; }
}
然后我在我的主要 controller 中將其初始化為 false:
public ActionResult Index()
{
CategoryItemViewModel CIVM = new CategoryItemViewModel();
CIVM.ItemList = GetItemModel();
CIVM.CategoryList = GetCategoryModel();
return View(CIVM);
}
public Item GetItemModel()
{
var dataFileItems = Server.MapPath("~/App_Data/Item.txt");
Item iModel = new Item()
{
userDataItems = System.IO.File.ReadAllLines(dataFileItems), //Items Text File
delimiterChar = new[] { ',' },
itemCheck = false,
};
return iModel;
}
然后我在我的視圖中使用它作為布爾值來指示復選框是否被勾選:
@using (Html.BeginForm("Items", "Items", FormMethod.Post, new { id = "formFieldTwo" }))
{
@Html.CheckBoxFor(m => m.ItemList.itemCheck, false)
}
最后,我嘗試訪問這個變量“itemCheck”,它應該在我的 ActionResult 中設置為“false”:
[HttpPost]
public ActionResult Items(string ItemDescription, CategoryItemViewModel m)
{
bool originalValue = m.ItemList.itemCheck;
var FkFile = Server.MapPath("~/App_Data/ForeignKeyValue.txt");
var Fk = System.IO.File.ReadAllText(FkFile);
var dataFileItems = Server.MapPath("~/App_Data/Item.txt");
var numberOfLinesItems = System.IO.File.ReadLines(dataFileItems).Count();
var textFileDataItems = ItemDescription + "," + numberOfLinesItems + "," + Fk + "," + originalValue + Environment.NewLine;
System.IO.File.AppendAllText(dataFileItems, textFileDataItems);
return View();
}
但是,我在“bool originalValue = m.ItemList.itemCheck;”行收到以下錯誤:
" System.NullReferenceException: '對象引用未設置為 object 的實例。' "
我不明白為什么我的程序給了我這個錯誤?
改變:
@Html.CheckBoxFor(m => m.ItemList.itemCheck, false)
至:
@Html.CheckBoxFor(Model => Model.ItemList.itemCheck, false)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.