【问题标题】:I'm new in ASP.NET CORE, and I'm trying to send data from dynamically created input fields to Controller我是 ASP.NET CORE 的新手,我正在尝试将数据从动态创建的输入字段发送到控制器
【发布时间】:2021-10-14 19:19:55
【问题描述】:

$("#addRow").click(function () 
         {
             @{
                 new VLSM_Model().LansValues.Add(new Lans());
             }
             var rowCount = parseInt($("#totalLans").val());
             rowCount++;
             $("#totalLans").val(rowCount);
                var html = '';
                html += '<div id="inputFormRow" style="width: 35%">';
                html += '<div class="input-group mb-3">';
                html += '<input type="number" id="[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
                html += '<div class="input-group-append">';
                html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
                html += '</div>';
                html += '</div>';
        
                $('#newRow').append(html);
            });
        
            $(document).on('click', '#removeRow', function () 
            {
                var rowCount = parseInt($("#totalLans").val());
                rowCount--;
                $("#totalLans").val(rowCount);
                $(this).closest('#inputFormRow').remove();
            });
            
            $(document).ready(function () {  
                    $("#createButton").click(function () 
                    {
                        var inputData = $(this).serializeArray();
                        $.ajax(  
                        {  
                            type: "POST", //HTTP POST Method  
                            url: "VLSM_Controller/Create", // Controller/View   
                            data: inputData,
                            success : function(response) {
                              console.log(response)
                            }
                        });  
              
                    });  
                });  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group" style="width: 35%">
                <label asp-for="IP_Address" class="control-label"></label>
                <input asp-for="IP_Address" class="form-control" />
                <span asp-validation-for="IP_Address" class="text-danger"></span>
            </div>
            <br/>
        <div class="form-group">
            <div id="inputFormRow" style="width: 35%">
                <div class="input-group mb-3">
                    <br/>
                    <div class="input-group-append"></div>
                </div>
            </div>
            <div id="newRow">
                 <input type="hidden" id="totalLans" value="0" />
            </div>
            <button id="addRow" type="button" class="btn btn-info">Add Network</button>
            
        </div>
            <span asp-validation-for="LansValues" class="text-danger"></span>
            <br/>
            <div class="form-group" style="width: 35%">
                <label asp-for="cidrValue" class="control-label"></label>
                <input asp-for="cidrValue" class="form-control" />
                <span asp-validation-for="cidrValue" class="text-danger"></span>
            </div>
            <br/>
            <div class="form-group">
                <input type="submit" value="Calculate VLSM" class="btn btn-info" id="createButton"/>
            </div>
        </form>
       
<div>
    <a asp-action="VlsmResult">Back to List</a>
</div>

正如您从代码中看到的那样,我创建了动态输入字段,但我很难将数据传递给控制器​​,并在控制器内部使用数据进行计算。

我的问题是如何将数据从使用 ajax 动态创建的输入字段传递到控制器,以及如何将传递的数据用于任何类型的计算。

【问题讨论】:

  • 请编辑您的问题并添加代码段以向我们展示您的控制器对 Create 方法的签名。
  • 这能回答你的问题吗? AJAX post doesn't send data .Net Core
  • 在上面链接的那个问题中,请注意控制器方法签名,以及在 AJAX 调用中如何定义数据属性(注意正在发送的值的名称如何与接受的参数匹配方法)
  • 您一直在强调动态创建的输入字段。但是字段是否“动态创建”(我认为您的意思是 JavaScript 函数)并在 HTML 文件中明确定义并没有任何区别。也许创建一个这样的“静态”HTML文件的例子,并展示对“动态”的更改如何使其不起作用。或者,如果您做不到 - 不要担心字段是动态的,并尝试使用 minimal reproducible example 重写问题

标签: ajax asp.net-core


【解决方案1】:

模型绑定系统将按名称查看属性。因此,您需要将 html 中的 name 属性与模型属性名称匹配。也就是说,你动态添加的输入字段应该有name属性:name="LansValues[index].InitialLanValues"

这是一个完整的工作演示:

型号:

public class VLSM_Model
{
    public string IP_Address { get; set; }
    public List<Lans> LansValues { get; set; }
    public int cidrValue { get; set; }
}
public class Lans
{
    public int InitialLanValues { get; set; }
}

查看:

type="submit"修改为type="button",否则ajax不会命中。

@model VLSM_Model
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group" style="width: 35%">
        <label asp-for="IP_Address" class="control-label"></label>
        <input asp-for="IP_Address" class="form-control" />
        <span asp-validation-for="IP_Address" class="text-danger"></span>
    </div>
    <br />
    <div class="form-group">
        <div id="inputFormRow" style="width: 35%">
            <div class="input-group mb-3">
                <br />
                <div class="input-group-append"></div>
            </div>
        </div>
        <div id="newRow">
            <input type="hidden" id="totalLans" value="0" />
        </div>
        <button id="addRow" type="button" class="btn btn-info">Add Network</button>    
    </div>
    <span asp-validation-for="LansValues" class="text-danger"></span>
    <br />
    <div class="form-group" style="width: 35%">
        <label asp-for="cidrValue" class="control-label"></label>
        <input asp-for="cidrValue" class="form-control" />
        <span asp-validation-for="cidrValue" class="text-danger"></span>
    </div>
    <br />
    <div class="form-group"> 
                @*change here*@
        <input type="button" value="Calculate VLSM" class="btn btn-info" id="createButton" />
    </div>
</form>

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

JS:

把动态html改成name="LansValues[' + (rowCount - 1) + '].InitialLanValues",把var inputData = $(this).serializeArray();改成var inputData = $('form').serializeArray();

@section Scripts
{
    <script>
    $("#addRow").click(function ()
    {
        @*@{new VLSM_Model().LansValues.Add(new Lans());}*@
        var rowCount = parseInt($("#totalLans").val());
        rowCount++;
        $("#totalLans").val(rowCount);
        var html = '';
        html += '<div id="inputFormRow" style="width: 35%">';
        html += '<div class="input-group mb-3">'; 

                //change id attribute to name attribute and modify the name
        html += '<input type="number" name="LansValues[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
        html += '<div class="input-group-append">';
        html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
        html += '</div>';
        html += '</div>';

        $('#newRow').append(html);
    });    
    $(document).on('click', '#removeRow', function ()
    {
        var rowCount = parseInt($("#totalLans").val());
        rowCount--;
        $("#totalLans").val(rowCount);
        $(this).closest('#inputFormRow').remove();
    });    
    $(document).ready(function () {
        $("#createButton").click(function ()
        {
            var inputData = $('form').serializeArray();   //change here...
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/Create", // Controller/View
                data: inputData,
                success : function(response) {
                    console.log(response)
                }
            });

        });
    });
    </script>
}

控制器:

public class HomeController : Controller
{
    [HttpPost]
    public IActionResult Create(VLSM_Model model)
    {
         //...
    }
}

注意:

其实如果你只是使用表单提交,它也可以很好地工作。如果您使用表单提交,只需在$("#addRow").click()函数中更改您的原始代码:name="LansValues[' + (rowCount - 1) + '].InitialLanValues" 。然后删除$("#createButton").click() 函数。无需更改任何其他代码。

【讨论】:

  • 非常感谢,数据正在传输中。我需要微调控制器。因为在我看来,除了值之外,还会显示一些字符串,例如:LansValues 10 20 30 System.Collections.Generic.List`1[VLSMVersion_3.Models.Lans]。你知道为什么会这样吗?
  • 我把所有东西都修好了。我工作得很好。非常感谢您的帮助。
猜你喜欢
  • 2020-10-04
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 2022-01-16
  • 2015-04-14
  • 2017-11-21
  • 1970-01-01
相关资源
最近更新 更多