within my model i have a bool value called itemCheck:
public class Item
{
public Array userDataItems { get; set; }
public char[] delimiterChar { get; set; }
public bool itemCheck { get; set; }
}
My viewModel, linking the item model to the controller:
public class CategoryItemViewModel
{
public Item ItemList { get; set; }
public Category CategoryList { get; set; }
}
Which i then initialize within my main controller as 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;
}
Then i use it in my view as the bool value to indicate whether a checkbox is ticked or not :
@using (Html.BeginForm("Items", "Items", FormMethod.Post, new { id = "formFieldTwo" }))
{
@Html.CheckBoxFor(m => m.ItemList.itemCheck, false)
}
And lastly i try to access this variable 'itemCheck' which should be set to 'false' within my ActionResult:
[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();
}
However, i get the following error on the line 'bool originalValue = m.ItemList.itemCheck;' :
" System.NullReferenceException: 'Object reference not set to an instance of an object.' "
I fail to understand why my program is giving me this error?
ItemList
in the statementm=>m.ItemList.itemCheck
? Your model shows that the property containingitemCheck
is callediModel
. Shouldn't this bem=>m.iModel.itemCheck
? You're missing a piece of the puzzle in your code examples. I would wager you are sending a list of theseItems
to the view and trying to use theHtml
editors for each item in the list. There are other ways that you have to use to access the properties of a collection of items in a view model like you are wanting. - Tommy