asp.net - 复选框助手返回空值的问题 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
.
解决方案
这可能是由于以下原因
- 为模型 ItemModel 引用了错误的命名空间。为确保您使用正确的模型,请使用
@model yourNamespace.ItemModel
- 构建问题。清理并构建项目。
推荐阅读
- django - 为什么我仍然收到“没有为范围类型'web socket'配置应用程序”?
- angular - 带纱线的 Angular CLI
- python - 带有“一般”异常消息的条件 `try` 语句
- docker - 在 Gitlab CI 上找不到 Docker 主机名
- reactjs - 当 React 使用 Canvas 时 - 绘图
- javascript - Thymeleaf:在控制器中为数据表定义 URL
- java - 让一个整数转到不同的行
- postgresql - postgres 使用 linux 命令从完整路径复制路径
- lisp - lisp - 错误:没有函数定义:BUTLAST
- django - 错误:未能将一些引用推送到“https://git.heroku.com/xxxxxxxxx.git”