Search code examples
javascriptc#razor-pagesasp.net-core-2.2

Razor Pages - Access razor view binded variable value after ajax get request on server


I'm trying to bind this variable on view so i don't need to send it through ajax call, not sure if that is possible but following the logic it looks like it would be.

    <script>

    $(function ()
    {
        GetStocksByUAP();
    });

    function GetStocksByUAP() {

        @{
            Model.Sector = "UAP1";
        }

        $.get('/dashboard/Index?handler=StocksBySector', function (response) {

                swal('OK', 'Dados carregados', 'success');
                console.log(response);



            });
    }

</script>

cs file

 [BindProperty]
    public string Sector { get; set; }


    public IndexModel(IConfiguration config)
    {
        _config = config;
    }

    public async Task<IActionResult> OnGetStocksBySectorAsync()
    {
        IDbConnection con = new SqlConnection(_config.GetConnectionString("DefaultConnection"));

        var result = await con.QueryAsync<DashboardViewModel>("GetStocksByUAP", new { UAP = Sector });

        return new JsonResult(result);
    }

To summit up, I'm trying to use the string Sector declared on the page and access it's value binded on the view after ajax get request on server. Not sure if this is possible though


Solution

  • If you want to process a value in a handler that gets called by an AJAX request using the GET method, you need to pass the value to the handler. You can do that as a query string value or as a route data value, but either way, it must be passed in the URL.

    If you want to bind the value to a PageModel property, you must specify SupportsGet = true in the BindProperty attribute:

    [BindProperty(SupportsGet=true)]
    public string Sector { get; set; }
    

    See more about how model binding works in Razor Pages here: https://www.learnrazorpages.com/razor-pages/model-binding#binding-data-from-get-requests