1
votes

Model:

 public class ItemModel
    {
        public bool IsChecked { get; set; }
    }

ViewModel:

 public class CategoryItemViewModel
    {
        public List<ItemModel> Item { get; set; }
    }

Index Controller:

public List<ItemModel> GetItemModel()
        {
            //Get fie path
            var ItemFile = Server.MapPath("~/App_Data/Items.txt");

            //Read from the Categories.txt file and display the contents in the List view
            List<ItemModel> item = new List<ItemModel>();

            //Read the contents of Category.txt file
            string txtData = System.IO.File.ReadAllText(ItemFile);

            //Execute a loop over the rows.
            foreach (string row in txtData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    item.Add(new ItemModel
                    {
                        IsChecked = Convert.ToBoolean(row.Split(',')[0])
                    });
                }
            }
            return item;
        }

The code above is basically reading items in a text file and then setting them to the model. I am having an issue when wanting to change the checked value of a checkbox, as the actual checkbox is returning a null value when I try check it, Problem code is below.

Controller to add a new line item with a checkbox:

[HttpPost]
public ActionResult Item(bool ItemCheck)
        {
            //Get file path of Categories.txt
            var ItemFile = Server.MapPath("~/App_Data/Items.txt");

            var ItemData = ItemCheck + Environment.NewLine;
            System.IO.File.AppendAllText(ItemFile, ItemData);

            return View();
        }

bool ItemCheck is returning a null value.

Index View code:

 foreach (var item in Model.Item)
 {
   @using (Html.BeginForm("Item", "Item", FormMethod.Post))
   {
     @Html.CheckBoxFor(ItemModel => ItemModel.IsChecked)
   }
 }

It is saying that ItemModel does not contain a definition for IsChecked.

1

1 Answers

0
votes

This could be due to the following reasons

  1. Referring wrong namespace for model, ItemModel. To ensure that you are using correct model use @model yourNamespace.ItemModel
  2. Build issue. clean and build the project.