Home > other >  I'm new in ASP.NET CORE, and I'm trying to send data from dynamically created input fields
I'm new in ASP.NET CORE, and I'm trying to send data from dynamically created input fields

Time:10-19

$("#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 >';
                html  = '<input type="number" id="['   (rowCount - 1)   '].InitialLanValues"  placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
                html  = '<div >';
                html  = '<button id="removeRow" type="button"  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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I created dynamically input fields as you can see from code, but I have difficulties to pass the data to controller, and to use the data for calculations inside the controller.

My question is how to pass data from dynamically created input fields with ajax to controller and how to use passed data for any kind of calculations.

CodePudding user response:

Model binding system will look through the property by name. So you need match the name attribute in html with model property name. That is to say, your dynamic added input fields should have name attribute:name="LansValues[index].InitialLanValues".

Here is a whole working demo:

Model:

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

View:

Modify type="submit" to type="button", otherwise the ajax will not hit.

@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:

Change the dynamic html to name="LansValues[' (rowCount - 1) '].InitialLanValues" and change var inputData = $(this).serializeArray(); to 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 >'; 

                //change id attribute to name attribute and modify the name
        html  = '<input type="number" name="LansValues['   (rowCount - 1)   '].InitialLanValues"  placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
        html  = '<div >';
        html  = '<button id="removeRow" type="button"  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>
}

Controller:

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

Note:

Actually if you just use form submit, it also can work well. If you use form submit, just change your original code:name="LansValues[' (rowCount - 1) '].InitialLanValues" in $("#addRow").click() function. Then remove the $("#createButton").click() function. No need change any other code.

  • Related