简体   繁体   中英

How to call a function from button in .NET Core Razor page

I want the user to be able to generate new input fields by the click of a button given a situation where the user would want to add additional information. It should also be possible to pass the amount of input fields to generate.

@{
Func<int, object> genInput =@<div class="generated">
    @{
        for (int i = 0; i < item; i++)
        {
            <input id="generatedInput[@i]" />
        }
    }
</div>;

@genInput(4);
<input id="amount" type="text" placeholder="Number of inputs to create"/>
<input type="button" onclick="genInput" />
}

I have created the function, but I don't know how to call it using the button or how to pass the amount of inputs to generate from the amount input along with it.

I have created the function, but I don't know how to call it using the button or how to pass the amount of inputs to generate from the amount input along with it.

You can not call the razor function from HTML by a button click, just do what you did like @genInput(4); is correct.

To meet your requirement, I suggest that you could do this by using Jquery.

As a workaround,here is the working demo:

@{
    Func<int, object> genInput =@<div class="generated">
        @{
            for (int i = 0; i < item; i++)
            {
                <input id="generatedInput[@i]" />
            }
        }
    </div>;

@genInput(4);
}

<input id="amount" type="text" placeholder="Number of inputs to create" />
<input type="button" onclick="add()" value="Create" />
<div id="new_chq"></div>
<input type="hidden" value="3" id="total_chq">

@section Scripts{
    <script>
        function add() {
            var amount = $("#amount").val();
            for (i = 0; i < parseInt(amount); i++) {
                var new_chq_no = parseInt($('#total_chq').val()) + 1;
                var new_input = "<input id='generatedInput[" + new_chq_no + "]' />";
                $('#new_chq').append(new_input);
                $('#total_chq').val(new_chq_no);
            }   
            $('#new_chq').append("<br/>");        
        }
    </script>
}

Result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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