Home > Net >  How to take result value of a jQuery script into a C# code in the same razor page in ASP.NET Core MV
How to take result value of a jQuery script into a C# code in the same razor page in ASP.NET Core MV

Time:12-15

I have used jQuery to find selected row index of a table. I need to use the result in C# code in the same razor page (Not in controller). I tried to use Ajax but I don't know what url I have to use. Please help me.

<script>
    var rowIndex;
    $(document).ready(function(){
        $('#pmElectrical').on("click", "tbody tr", function(){
            rowIndex = $(this).index();
            $.ajax({
                type: "POST",
                url: ????
                data: {_pmId: rowIndex},
                dataType: "text",
                success: function(){
                    alert(rowIndex);
                }
            });
        });
    });
</script>

CodePudding user response:

It seems you do not know the routing in razor pages. Here are several scenarios about routing.

Razor pages uses OnGet and OnPost to deal with the Http Get and Post request. If you need another Get or Post method in current PageModel, you need define the method name like: OnGetHandlerName or OnPostHandlerName.

How URLs are matched

By default, the route templates are generated by taking the virtual path of each content page and then removing the root folder name(Pages foler) from the start and the file extension from the end.

That is to say the route should be: /FolderName/PageName. If contains handler, it should be: /FolderName/PageName?handler=HandlerName.

For example:

Create a folder named Test in Pages folder. Then create an Create.cshtml. Location is:/Pages/Test/Create.cshtml.

enter image description here

This page default url should be: Test/Create. If in Create.cshtml.cs contains OnGetDisplay/OnPostDisplay handler and you need call this handler, the url should be:/Test/Create?handler=Display.

Notes:

One important thing you need know when your page is named Index.cshtml. Both of the following templates can match Index.cshtml:

"FolderName"          
"FolderName/Index"

Both of these routes will be mapped to the same virtual path: /<root>/FolderName/Index.cshtml.

This also indicates another thing, if you create a Test.cshtml page directly in root(Pages folder), the url is also:/Test. This will cause AmbiguousActionException. Please take care.


Route Templates

If you define Route Templates, Route Data parameters are defined in a Route Template as part of the @page directive in the .cshtml file.

@page "{title}"

The template created for this route is /FolderName/PageName/TitleName(e.g. /Test/Create/aaa).


How to use Ajax in Razor Pages

Razor Pages enable anti-forgery token validation by default, so you need add this token to header in ajax.

If you use form in Razor Pages, it will default generate an input with token. If not, you need add @Html.AntiForgeryToken() manually.


A whole working demo you could follow:

Page(Create.cshtml locates in /Pages/Test folder):

@page
@model WebApplication1.Pages.Test.CreateModel
@{
}

<table >
    <tr>
        <td>aa</td>
        <td>12</td>
    </tr>
    <tr>
        <td>bb</td>
        <td>15</td>
    </tr>
</table>
@Html.AntiForgeryToken()

@section Scripts
{
    <script>
        var rowIndex;
        $(document).ready(function () {
            $('tr').click(function () {
                rowIndex = $("tr").index(this);
                $.ajax({
                    type: "POST",
                    url: "/Test/Create",
                    data: { _pmId: rowIndex },
                    headers: {
                        RequestVerificationToken:
                            $('input:hidden[name="__RequestVerificationToken"]').val()
                    },
                    dataType: "text",
                    success: function () {
                        alert(rowIndex);
                    }
                });
            });
        });
    </script>
}

PageModel:

public class CreateModel : PageModel
{
    public void OnGet()
    {
    }
    public void OnPost(int _pmId)
    {

    }
}

Update:

If you use ASP.NET Core MVC, the url should be:/ControllerName/ActionName.

  • Related