gpt4 book ai didi

asp.net-core - 为什么 Bind 属性似乎破坏了嵌套对象的模型绑定(bind)?

转载 作者:行者123 更新时间:2023-12-02 06:45:17 25 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?我试图通过绑定(bind)参数操作来限制过度发布,但似乎它根本不起作用。当我删除 Bind 关键字时,一切都开始发挥作用。

这是代码示例:

查看模型:

public class ProductCreateViewModel
{
public Product Product { get; set; }
public ICollection<IFormFile> Images { get; set; }
}

行动:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Product.Id,Product.CategoryId,Product.Description,Product.Title")] ProductCreateViewModel productVM)
{
if (ModelState.IsValid)
{
_context.Add(productVM.Product);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["CategoryId"] = new SelectList(_context.Categories.Include(c => c.Categories).Where(c => c.ParentCategoryId == null), "Id", "Name", productVM.Product.CategoryId);
return View(productVM);
}

查看:

@model CatalogWebApp.Models.ProductsViewModels.ProductCreateViewModel

@{
ViewData["Title"] = "Add Product";
ViewData["BigPageTitle"] = "Products";
ViewData["PageBoxTitle"] = "Add New Product";
}

<form asp-action="Create">
<div class="form-horizontal">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Product.CategoryId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select name="Product.CategoryId" class ="form-control">
@foreach(Category item in (ViewBag.CategoryId as SelectList).Items)
{
<option value="@item.Id">@item.Name</option>
if (item.Categories != null && item.Categories.Count > 0)
{
foreach (var subCat in item.Categories)
{
<option value="@subCat.Id">--@subCat.Name</option>
}
}
}
</select>
</div>
</div>
<div class="form-group">
<label asp-for="Product.Description" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Product.Description" class="form-control" />
<span asp-validation-for="Product.Description" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Product.Title" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Product.Title" class="form-control" />
<span asp-validation-for="Product.Title" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>

<div>
<a asp-action="Index">Back to List</a>
</div>

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

有人可以指出我是否有问题或者这只是一个已知的 asp.net core 问题吗?

最佳答案

我不太清楚您为什么在您的案例中使用 Bind

只需创建单独的 ViewModel,其中仅包含您需要的属性,例如 ProductCreateStort

然后在您的 Controller 签名中使用此 ViewModel 并从中继承您的主模型。

这样您就不会弄乱 Bind 并限制 POST 上的参数

关于asp.net-core - 为什么 Bind 属性似乎破坏了嵌套对象的模型绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com