【发布时间】:2020-08-13 13:47:14
【问题描述】:
在我的模型中,我有一个名为 itemCheck 的布尔值:
public class Item
{
public Array userDataItems { get; set; }
public char[] delimiterChar { get; set; }
public bool itemCheck { get; set; }
}
我的 viewModel,将项目模型链接到控制器:
public class CategoryItemViewModel
{
public Item ItemList { get; set; }
public Category CategoryList { get; set; }
}
然后我在我的主控制器中将其初始化为 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: '对象引用未设置为对象的实例。' "
我不明白为什么我的程序给了我这个错误?
【问题讨论】:
-
声明
m=>m.ItemList.itemCheck中的ItemList是什么?您的模型显示包含itemCheck的属性称为iModel。这不应该是m=>m.iModel.itemCheck吗?您在代码示例中遗漏了一块拼图。我敢打赌,您会将这些Items的列表发送到视图,并尝试对列表中的每个项目使用Html编辑器。您必须使用其他方法来访问视图模型中项目集合的属性,就像您想要的那样。 -
抱歉,我已经将另一部分上传到我的模型中,我这样做的原因是能够在单个视图中使用来自多个模型的变量。
-
@Tommy 我已经更新了我的问题,希望你能看到发生了什么。如果我对您的任何建议有些不确定,我深表歉意。 ASP.NET 和 MVC 对我来说都是非常新的概念。
标签: c# asp.net asp.net-mvc asp.net-mvc-4 model-view-controller