我有一个带有类别列表的索引视图。单击以编辑其中之一时,可以在同一视图中“内联”编辑它。但是我无法从复选框中获得true
。如果我在数据库中手动将Published
设置为true
,则会选中该复选框,但是提交后会将其设置回false
。
这是视图模型:
public class ProductCategoryVM
{
public int Id { get; set; }
public string Title { get; set; }
public bool Published { get; set; }
}
视图的剃须刀代码(请注意,即使我有一个类别列表,我也只编辑其中一个类别-Model[i].Id == id
所在的类别。):
@model List<ProjectName.Models.ViewModels.ProductCategoryVM>
string action = this.ViewContext.RouteData.Values["action"] != null
? this.ViewContext.RouteData.Values["action"].ToString()
: "";
int id = this.ViewContext.RouteData.Values["id"] != null
? int.Parse(this.ViewContext.RouteData.Values["id"].ToString())
: 0;
for (var i = 0; i < Model.Count(); i++)
{
if (Model[i].Id == id && action == "Edit")
{
<form asp-action="Index">
<input type="hidden" asp-for="@Model[i].Id" name="Id" />
<input asp-for="@Model[i].Title" name="Title" />
@Html.CheckBoxFor(m => Model[i].Published)
<button type="submit">Save</button>
</form>
}
else if (Model[i].Id == id && action == "Delete")
{
// Confirm delete.
}
else
{
// List out the rest of the categories with link to Edit and Delete:
<a asp-action="Index"
asp-route-action="Edit"
asp-route-id="@Model[i].Id">Edit</a>
<a asp-action="Index"
asp-route-action="Delete"
asp-route-id="@Model[i].Id">Delete</a>
@Model[i].Title
}
}
这是Title
和Published
的HTML输出:
<input name="Title" type="text" id="z1__Title" value="Test category" />
<input id="z1__Published" name="[1].Published" type="checkbox" value="true" />
在这种情况下,类别通过Title = "Test category"
和Published = false
保存到数据库。
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(int id, string action,
[Bind("Id,Published,Title")] ProductCategory productCategory)
{
if (ModelState.IsValid)
{
switch (action)
{
case "Create":
// Create a new category
case "Edit":
_context.Update(productCategory);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
case "Delete":
// Delete a category
default:
return RedirectToAction(nameof(Index));
}
}
return View(productCategory);
}