简体   繁体   English

ASP.NET Core Model 使用jquery中继器绑定

[英]ASP.NET Core Model Binding using jquery repeater

There are many similar question yet I don't find any suitable answers.有很多类似的问题,但我找不到合适的答案。

I use Jquery repeater repeater and repeater is working fine but I can not bind my model as input name doesn't match my model name.我使用 Jquery 中继,中继器工作正常,但我无法绑定我的 model,因为输入名称与我的 model 名称不匹配。

So I followed this answer answer and changed the input name group-a[0][text-input] to group-a[0].text-input which works perfectly fine for the first input but as soon as I add next row input name becomes group-a[0].0所以我按照这个答案answer并将输入名称 group-a[0][text-input] 更改为 group-a[0].text-input 这对于第一个输入来说工作得很好但是一旦我添加下一行输入名称变为 group-a[0].0

Now again I can't bind my model.现在我又不能绑定我的 model。

I want to ask how to solve this issue or please suggest me any better approach to bind the model. I've been searching for some days but still didn't get the answer and I'm also a beginner.我想请教如何解决这个问题,或者请给我一些更好的绑定model的方法。我已经搜索了几天,但仍然没有得到答案,我也是初学者。 Thank you谢谢

enter code here public class CreatePurchaseOrderModel
{
    [Required(ErrorMessage ="Vendor name is required")]
    public string VendorId { get; set; }

    public List<ProductDetails> ProductDetails { get; set; }

    [Required]
    public decimal TotalPrice { get; set; }
    public decimal VatAmount { get; set; }
    [Required]
    public decimal NetAmount { get; set; }
    public bool IsVatType { get; set; }
    public List<VendorModel>? Vendor { get; set; }
}

public class ProductDetails
{
    [Required(ErrorMessage = "Product name is required")]
    public string ProductId { get; set; }

    [Required(ErrorMessage = "Quantity  is required")]
    public int Quantity { get; set; }

    [Required(ErrorMessage = "Rate  is required")]
    public decimal Rate { get; set; }
}


enter code here public async Task<IActionResult> CreatePurchaseOrder(CreatePurchaseOrderModel model)
    {

        if (ModelState.IsValid)
        {
            var response = await _iPurchaseOrderService.CreatePurchaseOrder(model);
            if (response.IsSuccessStatusCode)
            {
                var responseMessage = await response.Content.ReadAsAsync<ResponseMessageModel>();
                if (responseMessage.ResponseMessage == ResponseMessage.PurchaseOrderCreatedSucessfully)
                {
                    TempData["Success"] = ResponseMessage.PurchaseOrderCreatedSucessfully;
                    return RedirectToAction("Index", "PurchaseOrder");
                }
            }
            TempData["Error"] = $"Something went wrong";
            return RedirectToAction("Index", "PurchaseOrder");
        }
        await InitializedViewBagAsync();
        var vendorListResponse = await _iPurchaseOrderService.GetAllVendorList();
        if (vendorListResponse.IsSuccessStatusCode)
        {
            var vendorList = await vendorListResponse.Content.ReadAsAsync<List<VendorModel>>();
            var vendorListmodel = new CreatePurchaseOrderModel()
            {
                Vendor = vendorList
            };
            return View(vendorListmodel);
        }
        return View(model);
    }

Your error was caused by this code:您的错误是由以下代码引起的:

var matches = $input.attr('name').match(/\[[^\]]+\]/g);

 var name = matches ?
  // strip "[" and "]" characters
 last(matches).replace(/\[|\]/g, '') :
 $input.attr('name');
                        

 var newName = groupName + '[' + index + '].' + name +($input.is(':checkbox') || $input.attr('multiple') ? '[]' : '');

 $input.attr('name', newName);

The code reads name from last value inside [] ,and I logged the values of newName, you could see how it works:代码从[]中的最后一个值读取名称,我记录了 newName 的值,您可以看到它是如何工作的:

Test1:测试一:

在此处输入图像描述

Test2:测试2:

在此处输入图像描述

To bind your model,I think it's more convenient if you would add js codes to change the input name when you submit the form rather than modify the logic in jQuery.绑定你的model,我觉得提交表单的时候加上js代码修改输入名称比修改jQuery里面的逻辑更方便。

I tried as below:我尝试如下:

<script>
    var items = document.getElementsByClassName("product");
    $('#save').click(function () {
        for (var i = 0; i < items.length; i++)
        {
            items[i].setAttribute("name", "ProductDetails["+i+"].ProductId")
        }        
    });
</script>

...... ……

<div data-repeater-list="">
        <div data-repeater-item="">
            <div class="col-lg-12 col-md-12 col-sm-12">
                <input  class="product"name="ProductId" />               
            </div>
        </div>
    </div>
<input data-repeater-create type="button" value="Add" />
    <input id="save"type="submit" value="Save" />

The result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM