仅发布检查值到视图模型

问题描述 投票:1回答:1

我在使表单模型中的检查值正确发布方面遇到一些麻烦。

我有这个Product

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Photo { get; set; }
    public int InStock { get; set; }
    public decimal Price { get; set; }
    public decimal Discount { get; set; }
    public decimal TotalPrice => Price - Discount;
    public int SupplierId { get; set; }
    public string SupplierName { get; set; }
    public IEnumerable<Category> Categories { get; set; }//Contains only the categories the product is bound to
}

还有这个Category

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

还有这个EditVM

public class EditVM
{
    public Product Product { get; set; }
    public IEnumerable<Category> Categories {get; set;}//Contains all the categories in the db
}

在我的ProductController中,我有Edit操作方法。

public async Task<IActionResult> Edit(int id)
{
    var product = await _productRepo.Get(id);
    if (product == null) return RedirectToAction(nameof(Index));
    var categories = await _categoryRepo.Get();
    var editVM = new EditVM()
    {
        Product = product,
        Categories = categories
    };
    return View(editVM);
}

这是我在视图中循环浏览类别的HTML

@{var categoryIdList = @Model.Product.Categories.Select(x => x.Id); //Again, contains only the categories the Product is bound to (And gets the id's)
int counter = 0;}
@foreach (Category category in Model.Categories)//Loop through all the categories in the db
{
    if (categoryIdList.Contains(category.Id))
    {
        <input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" checked />
    }
    else
    {
        <input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" />
    }
    <input type="hidden" name="Product.Categories[@counter].Id" value="@category.Id" />
    <label>@category.Name</label>
    { counter++;}
}

到目前为止,一切都很好,到这里为止一切正常。如果我在数据库中有5个类别,并且产品绑定到其中2个类别,则会显示5个复选框,并选中2个复选框。所以这很完美。

但是,问题出在我选择或取消选择复选框时。现在,数据库中的每个Categories.Id(选中或未选中)都将发布到HttpPost Edit操作方法中,而我只希望选择发布的ID。

[HttpPost]
//Note the Product class contains an IEnumerable<Category> Categories prop for the categories the propduct is bound to. This is where the chechbox values must come in play...
public async Task<IActionResult> Edit(Product Product)
{
    var EditedProduct = await _productRepo.Update(Product);
    return RedirectToAction(nameof(Index));
}

我可以选择制作一个EditPostVM,但这并不是我的喜好。 (但这不是我的问题的解决方案!)

c# arrays checkbox asp.net-core-mvc model-binding
1个回答
0
投票

您在foreach循环中有一个隐藏的输入,它将所有类别发送到后期编辑。只需将其删除:

<input type="hidden" name="Product.Categories[@counter].Id" value="@category.Id" />
© www.soinside.com 2019 - 2024. All rights reserved.