How to add client click event to div to call method in ASP.NET Core 2.2 Razor page

2.2k Views Asked by At

I made a calendar in a Razor page, and I want to make each date (a div) clickable so they call a method and pass it the clicked date (div id set to date). I'm generating the calendar in the cs page and I'm not using MVC controllers.

@model Budget.Pages.CalendarModel
@{
    ViewData["Title"] = "Calendar";
}
<form method="post">
    @Html.Raw(Model.getCal())
</form>

And then in my cs page I have the method getCal() that generates a calendar via divs, css and some math, which is working fine, but I need to attach onClick events to each day (div).

public string getCal() 
        {
            //I won't print out all of my calendar generation code in ordfer to simplify this question.
            //The code below happens in a loop where the MM, DD and YYYY change as appropriate to be 
            //unique. This is where I want to put my onclick events to call another method, onDateSelect(this.id)

            retValue += "<div id='" + MM + "_" + DD + "_" + YYYY + "' class='col-md-9 dayCell'>" +
                            strDayNo +
                        "</div>";
            return retValue; //When out of loop of course
        }
1

There are 1 best solutions below

0
Nan Yu On

After rendering the content with @Html.Raw(Model.getCal()) in your page , you can add click event on your div :

@section Scripts{ 

    <script>
        $(document).on('click', ".dayCell", function () {


        });

    </script>

}

Razor Pages are designed to be protected from (CSRF/XSRF) attacks. Hence, Antiforgery token generation and validation are automatically included in Razor Pages. Please refer to below article for code sample :

Handle Ajax Requests in ASP.NET Core Razor Pages

Here is code sample based on your requirement :

@section Scripts{ 

    <script>
        $(document).on('click', ".dayCell", function () {

            $.ajax({
                type: "POST",
                url: "/YourPageName?handler=Send",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                data: JSON.stringify({
                    ID: this.id

                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {

                },
                failure: function (response) {
                    alert(response);
                }
            });
        });



    </script>

}

Server side function :

public JsonResult OnPostSend([FromBody]PostData value)
{
    ....
}
public class PostData
{
    public string ID { get; set; }
}

Also configure the antiforgery service to look for the X-CSRF-TOKEN header:

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");