首页 > 解决方案 > 复选框助手返回空值的问题 ASP.NET MVC

问题描述

模型:

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

视图模型:

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

索引控制器:

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;
        }

上面的代码基本上是读取文本文件中的项目,然后将它们设置到模型中。我想更改复选框的选中值时遇到问题,因为当我尝试检查它时实际的复选框返回空值,问题代码如下。

控制器添加带有复选框的新行项目:

[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正在返回一个空值。

索引查看代码:

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

意思是 ItemModel 不包含IsChecked.

标签: asp.netasp.net-mvcmodel-view-controller

解决方案


这可能是由于以下原因

  1. 为模型 ItemModel 引用了错误的命名空间。为确保您使用正确的模型,请使用@model yourNamespace.ItemModel
  2. 构建问题。清理并构建项目。

推荐阅读