[英]Cant add value to list c# mvc asp.net
I would like to add parts to a product in my web app but this only seems to work if its hardcoded.I've put the same code in the function and everything seems to work (in the console) but when creating the product the parts wont show in the detail page.The values wont bind to the list.. 我想在我的Web应用程序中向产品中添加零件,但这似乎只有在对其进行硬编码的情况下才有效。我已经在函数中添加了相同的代码,并且一切似乎都正常(在控制台中),但是在创建产品时零件不会显示在详细信息页面中。值不会绑定到列表。
line break on if(Modelstate.IsValid) shows: Parts null if(Modelstate.IsValid)上的换行符显示:零件null
create controller 创建控制器
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(AddProductViewModel viewModel)
{
if (ModelState.IsValid)
{
_context.Add(viewModel.Product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View();
}
Create product view 创建产品视图
@model IctWizard.ViewModel.AddProductViewModel @{ ViewData["Title"] = "Create"; } <script> var i = 0; jQuery('document').ready(function ($) { $('#plus').click(function () { inputValues = $('#partInput').val(); content = $('#partInput :selected').text(); console.log(content); $("#parts").find("tbody").append("<tr><td><input asp-for=\\"Product.ProductParts[" + i + "].PartId\\" value=\\"" + inputValues + "\\" /></td></tr>"); console.log($("#parts").find("tbody")); i++; }); }) </script> <h1>Create product</h1> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Product.ProductName" class="control-label">Product name</label> <input asp-for="Product.ProductName" class="form-control" /> <span asp-validation-for="Product.ProductName" class="text-danger"></span> </div> <div> </div> <div class="form-group"> <label asp-for="Product.ProductPrice" class="control-label">Product price</label> <input asp-for="Product.ProductPrice" class="form-control" /> <span asp-validation-for="Product.ProductPrice" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Product.ReleaseDate" class="control-label">Release date</label> <input asp-for="Product.ReleaseDate" class="form-control" /> <span asp-validation-for="Product.ReleaseDate" class="text-danger"></span> </div> <div class="form-group"> <label class="control-label"></label> <select name="Part" id="partInput"> @foreach (var part in Model.Parts) { <option value="@part.Id">@part.Description</option> } </select> <div class="btn btn-primary" id="plus">Add part</div> </div> <div class="row"> <div class="col-sm-12"> <table id="parts"> <thead> <tr> </tr> </thead> <tbody><tr><td> @** <input type="hidden" asp-for="Product.ProductParts[0].PartId" value="7" /> <input type="hidden" asp-for="Product.ProductParts[0].PartId" value="6" /> <input type="hidden" asp-for="Product.ProductParts[1].PartId" value="7" /> <input type="hidden" asp-for="Product.ProductParts[2].PartId" value="8" /> <input type="hidden" asp-for="Product.ProductParts[0].Quantity" value="2" /> <input type="hidden" asp-for="Product.ProductParts[1].Quantity" value="5" /> <input type="hidden" asp-for="Product.ProductParts[2].Quantity" value="9" />*@ </td> </tr> </tbody> </table> </div> </div> <div class="form-group"> <hr/> <input type="submit" value="Create product" class="btn btn-primary" style="margin-top: 10px"/> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
Product model 产品型号
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace IctWizard.Models { public class Product { public int Id { get; set; } public string ProductName { get; set; } public int ProductPrice { get; set; } [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } public IList<ProductPart> ProductParts { get; set; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace IctWizard.Models { public class ProductPart { public int ProductId { get; set; } public int PartId { get; set; } public Product Product { get; set; } public Part Part { get; set; } [Required] public int Quantity { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using System.Data.SqlClient; using System.IO; using System.Text; namespace IctWizard.Models { public class Part { public int Id { get; set; } [Required] public string Description { get; set; } public IList<SupplierPart> SupplierParts { get; set; } public IList<ProductPart> ProductParts { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IctWizard.Models; namespace IctWizard.ViewModel { public class AddProductViewModel { public Product Product { get; set; } public IList<Part> Parts { get; set; } } }
In .net core, VS allows asp-for to give you IntelliSense, however upon the page rendering, Razor generates additional HTML for you. 在.net core中,VS允许as-for为您提供IntelliSense,但是在页面呈现时,Razor会为您生成其他HTML。
When you hard code a hidden input, it will work because it correct adds all of the HTML attributes necessary for model binding to correctly occur when posting the form. 当您对隐藏的输入进行硬编码时,它将起作用,因为它可以正确添加模型发布时正确进行模型绑定所必需的所有HTML属性。
To correct for this, you need to look at your HTMl after it is rendered to figure out how to recreate what the Razor engine has done for you in Javascript. 要对此进行更正,您需要在呈现HTM1之后对其进行检查,以弄清楚如何用Javascript重新创建Razor引擎为您完成的工作。
For this example, try changing your JS to do the following (adding the name attribute and dropping the asp - model binding is expecting the name attribute. ): 对于此示例,请尝试更改JS以执行以下操作(添加name属性并删除asp-模型绑定需要name属性。):
<script>
var i = 0;
jQuery('document').ready(function ($) {
$('#plus').click(function () {
inputValues = $('#partInput').val();
content = $('#partInput :selected').text();
console.log(content);
$("#parts").find("tbody").append("<tr><td><input for=\"Product.ProductParts[" + i + "].PartId\" name=\"Product.ProductParts[" + i + "].PartId\" value=\"" + inputValues + "\" /></td></tr>");
console.log($("#parts").find("tbody"));
i++;
});
})
</script>
Check this out for more information: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-2.2 签出更多信息: https : //docs.microsoft.com/zh-cn/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-2.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.