首页 > 解决方案 > 无法将值添加到列表 c# mvc asp.net

问题描述

我想在我的网络应用程序中向产品添加部件,但这似乎只有在硬编码时才有效。我在函数中放入了相同的代码,一切似乎都正常工作(在控制台中)但是在创建产品时部件不会显示在详细信息页面中。值不会绑定到列表..

if(Modelstate.IsValid) 上的换行显示:Parts null

创建控制器

        // 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();
    }

创建产品视图

@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");}

}

产品型号

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; }


       }
}
添加ProductViewModel
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; }
    }
}

标签: javascriptc#asp.net-mvc

解决方案


在 .net core 中,VS 允许 asp-for 为您提供 IntelliSense,但是在页面呈现时,Razor 会为您生成额外的 HTML。

当您对隐藏的输入进行硬编码时,它会起作用,因为它正确地添加了模型绑定所需的所有 HTML 属性,以便在发布表单时正确发生。

要纠正此问题,您需要在呈现 HTMl 后查看它,以了解如何重新创建 Razor 引擎在 Javascript 中为您完成的工作。

对于此示例,尝试更改您的 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>

查看更多信息: https ://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-2.2


推荐阅读