简体   繁体   English

无法将值添加到列表C#MVC ASP.NET

[英]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; } } } 
ProductPart ProductPart
 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; } } } 
Part model 零件模型
 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; } } } 
AddProductViewModel AddProductViewModel
 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.

相关问题 如何使用 ASP.NET Core 3.1 MVC 中的 ViewModel 与 JavaScript 和 C# 动态添加到列表 - How to dynamically add to list with ViewModel in ASP.NET Core 3.1 MVC with JavaScript and C# 在c#代码中连接值到值 - Asp.net MVC - concatenating value to value in c# code — Asp.net MVC 我可以将预先存在的 Javascript 代码添加到 ASP.NET MVC C# 应用程序吗 - Can I add pre-existing Javascript code to an ASP.NET MVC C# application 您如何序列化JS数组,以便Asp.net MVC可以将其绑定到ac#列表? - How do you serialize a JS array so Asp.net MVC can bind it to a c# list? 如何将值从javascript变量传递给asp.net mvc中的c#变量 - how to pass a value from javascript variable to c# variable in asp.net mvc 从AJAX中的javascript向C#方法发布请求,无返回值,ASP.NET,MVC - Posting request from javascript in AJAX to C# methods, no returning value, ASP.NET, MVC 如何在asp.net mvc中使用razor viewmodel将c#guid值赋给javascript变量? - How to assign c# guid value to javascript variable using razor viewmodel in asp.net mvc? 在C#代码中引用jquery变量(ASP.NET MVC) - Referencing jquery variables in C# code (ASP.NET MVC) 在JavaScript中镜像C#模型-ASP.NET MVC - Mirroring C# Models in JavaScript - ASP.NET MVC Asp.net mvc将C#对象传递给Javascript - Asp.net mvc passing a C# object to Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM