How can I send a JsonResult back to a Razor Page?

I am just starting out with ASP.net and Razor Pages. In the code snippet below, my aim is to populate the District dropdown list based on the selected value from the State dropdown list. This is what I have managed to come up with so far:

View:

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascirpt" type="text/javascript">
    function GetDist(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#select-state").html(procemessage).show();
        var url = "/Info/GetDistById/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Quận/Huyện</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#select-state").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>

<div class="col-md-offset-0 col-md-2">
            <select class="form-control" id="select-state" onchange = "javascript:GetDist(this.value);">
                @foreach (var state in Model.tbState)
                {
                    <option <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483e29243d2d75083b3c293c2d661b3c293c2d012c">[email protected]</a>>@state.Statename</option>
                }
            </select>
        </div>
        <div class="col-md-1 ">Quận/Huyện: </div>
        <div class="col-md-offset-0 col-md-2">
            <select class="form-control" id="select-dist">
                @foreach (var dist in Model.tbDistrict)
                {
                    <option <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e197808d9484dca185889295cfa588929593888295a885">[email protected]</a>>@dist.Districtname</option>
                }
            </select>
        </div>

In my cshtml.cs file, I have the following code. I have used System.Web.Helpers at the beginning of the code:

public IActionResult GetDistById(int stateid)
        {
            List<TbDistrict> list = new List<TbDistrict>();
            foreach (var q in tbDistrict)
            {
                if (q.StateId == stateid)
                    list.Add(q);
            }
            SelectList selectlist = new SelectList(list, "", "", 0);
            JsonResult result = Json(selectlist);
            return result;
        }

I discovered that the Json() method only functions with the Controller class in MVC, and not with a Razor PageModel class. This leads to error CS0103 "The name 'Json' does not exist in the current context". Is there a workaround to resolve this issue?

Answer №1

There seem to be several issues at hand.

  1. To receive JSON in return, consider trying the suggestion from @poke which involves using return new JsonResult as shown below:

    public IActionResult OnGetDistById(int stateid)
    {
        return new JsonResult(new Product { Id = stateid, Name = "Tom" });
    }
    
  2. In the action method of PageModel, ensure that its name follows the recommendation from @Prakash, using OnGetDistById.

  3. For the client-side, the request URL should be

    https://localhost:44358/index?handler=distbyid&stateid=2
    , specifying the handler and query string stateid.

If you prefer a request URL like /Info/GetDistById/, you will need to implement a web API in your razor project instead of using PageModel.

Follow these steps:

  1. Add a ValuesController to your project like so:

    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
            // GET: api/<controller>
            [HttpGet]
            public IEnumerable<string> Get()
            {
            return new string[] { "value1", "value2" };
            }        
    }
    
  2. Configure the route in Startup.cs:

    app.UseMvc(routes =>
    {
            routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
    });
    

Answer №2

When using ASP Pages, the standard methods are OnGet and OnPost. However, if you require additional calls to the same page using Ajax, you must adhere to the OnGet* and OnPost* naming convention.

For instance, in the specific example provided, you would name the method as OnPostDistById and define the URL in Javascript as "/Info/DistById". If it were a HTTP Get call instead, the method name would change to OnGetDistById, but the URL would remain the same.

For further information, refer to the link here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to Generating Extern for a Constant Variable in Google Closure Compiler (Variable Cannot be Renamed due to Eval)

Currently, I am using Google Closure Compiler in "SIMPLE_OPTIMIZATIONS" mode for my JavaScript code. However, I encountered an issue when the obfuscation changed the variable name from "_u" to "a", resulting in an error that "_u" is not defined in the cons ...

When using Inertia.js with Laravel, a blank page is displayed on mobile devices

Recently, I've been working on a project using Laravel with React and Inertia.js. While everything runs smoothly on my computer and even when served on my network (192.168.x.x), I encountered an issue when trying to access the app on my mobile phone. ...

Attempting to manipulate the selected tab material using a custom directive with two-way data binding

I've been struggling to change the tab using code and can't seem to figure out what's causing the error. It works fine when I use the controller to change the variable, but when trying to bind it through a directive, it breaks. var app = an ...

transferring double quotation marks and square brackets through a parameter

I have an angularjs (1.x) scope set up as follows: $scope.report = { resource: '/public/emplyACH', params: { "employeeId": [78] } }; When I try to access it using console.log (console.log(scope.parms)) I see the output as ...

jQuery Validate enabling submission even with invalid fields

I have encountered an issue with validation on an ASP.NET MVC form that uses jQuery Validate. The form contains multiple fields, all of which validate correctly except for the last field called 'AmtRemaining'. This particular field has an initial ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

The ASP.Net Core razor page handler transforms into a versatile all-encompassing route

I recently updated my ASP.Net Core 3.1 Razor Pages project to utilize routing-based handler methods by changing @page to @page "{handler?}" in the Index.cshtml file. While this change has been successful, I have encountered an issue where the page now ac ...

Adjust the size of a div element after updating its content using Mootools

I am currently utilizing mootools 1.2 on a basic webpage. There is a div that contains a form (referred to as formdiv) which is submitted through JS/ajax. Once the ajax request returns a "confirmation message" data, the formdiv updates accordingly. The is ...

Steps for resetting data() on a route without parameters:

Having trouble restarting a route on a new editor I have a specific route /editor as well as /editor?_id=dasd448846acsca The /editor route consists of a simple form with empty inputs, while the /editor?_id=dasd448846acsca route has the same component bu ...

Tips for stopping variables from leaking in JavaScript

I'm currently working on a JavaScript code for my task manager website. Each page has its own JS file, but I've noticed that the data saved in one file seems to leak over to the others. How can I contain these variables so that tasks don't s ...

"Enjoying a table header that scrolls freely with autoscroll feature

Resolved - http://jsfiddle.net/CrSpu/11704/ I'm facing an issue with a table that has autoscroll functionality. I am looking to freeze the header of the table when automatic scrolling occurs, or you can test it out using my code pen. I'm uncer ...

Utilize the conditional GET method when including scripts through tags in an HTML webpage

Is it possible to benefit from HTTP conditional requests when including a script in the head section of a page? My goal is to cache dynamically downloaded JavaScript files that are added to the head section using script tags. If this approach isn't fe ...

Adding a function into a node within PostgreSQL

Hi there, I'm currently following a tutorial and attempting to execute a simple insert query, however, I keep encountering a 404 error. I am using Postman to input values. function function insertUser(req, res, next){ req.body.users = parseInt(r ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Permanently dismiss Bootstrap 4 alert using a cookie

Recently, I came across a bootstrap 4 alert that I found quite useful. Here is the code snippet for it: <div class="alert alert-warning alert-dismissible fade show" role="alert"> <button type="button" class="clo ...

Discovering the selected row with jqueryIs there a way to locate

There is a table with rows and a button that allows you to select a row: <table id="mytable" class="table-striped"> <tbody> <tr id="1"><td>Test1</td></tr> <tr id="2"><td>Test2</td>& ...

Modifying the Color of Individual Items within the Pagination Component in MUI

I am attempting to modify the background color of every item in my Pagination component by utilizing makeStyles. import { Pagination } from "@material-ui/lab"; import { makeStyles } from "@material-ui/core"; const pagination = makeStyl ...