user4041263
user4041263

Reputation:

How handle event like click in RazorPages by C# functions

I want to call a C# function when I click on a button, or select an item in selectList on the razor page. In blazor , it is possible like this code:

<button class="btn btn-info form-control" @onclick="AddNewCategory" >Add New Category</button>

but in razor page, I can't use it Please help me!

Upvotes: 0

Views: 1306

Answers (1)

Yiyi You
Yiyi You

Reputation: 18159

If you want to select an item in selectList on the razor page when clicking on a button,you can try to use js,here is a demo.When clicking the button,the selected value will be 4.

    <select id="select1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    
    </select>
    <button onclick="changeSelectedItem()">test</button>
    @section Scripts{
        <script>
            function changeSelectedItem() {
                $("#select1").val(4);
            }
        </script>
    } 

And if you want to call a C# function when I click on a button,you can use ajax to call a handler.here is a demo:

cshtml:

 @Html.AntiForgeryToken()
    <button onclick="callHandler()">callHandler</button>
    @section Scripts{
        <script>
            function callHandler() {
                 $.ajax({
                    type: "POST",
                    url: "?handler=TestHandler",
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    success: function (data) {
                       //...
                    }
    
                });
            }
     </script>
    } 

cshtml.cs:

public void OnPostTestHandler()
{ 
    //do something here
}

Upvotes: 1

Related Questions