pass data from javascript to asp.net core 2 razor page method

5.1k views Asked by At

Is there any to pass some data from HTML property on changed event data to asp.net core razor pages? I want to get an ID from dropdown list from HTML using JS and pass it to Razor Pages (asp.net core 2) and get the result from the custom method ? Code I want to be look like below if possible :)

JS code

$('#Neighborhood_DistrictId').on('change', function () {
    @Model.GetDistrictName($('#Neighborhood_DistrictId').val());
});

On the Razor page

public string GetDistrictName(Guid id)
{
    return httpSystemApi.GetByIdAsync<District>("Districts", id).Result.Name;
}

GetDistrictName method is connecting to API and returning the value. I don't want to direct connect to API with JS if there is a way to do what I want

2

There are 2 answers

1
umasankar On
$('#Neighborhood_DistrictId').on('change', function () {
    @Model.GetDistrictName($('#Neighborhood_DistrictId').val());
});

@Model.GetDistrictName is a server side method not Usage directly inside script

$('#Neighborhood_DistrictId').on('change', function () {
  var url="http://localhost/{controllername}/{methodname}/id=";
  url=url+$('#Neighborhood_DistrictId').val()
$.get(url,function(data){
...some code
});
});

var url="http://localhost/{controllername}/{methodname}/id=";

In mvc 5 genrate url from server side and set the client side variable

var url='Url.Action("{action}","{controllername}","actionname")';

this is only way for call the controller using javascript or jquery not Directly use server side method in javascript.

0
Kirit Chandran On

I am playing around with Razor Pages, and I have the same issue. Below is my work around. It seems like there should be some event handler will do the same thing, but I have not found another way yet. I tried treating it like the MVC controller, but I believe there is some form token that it is expecting so that did not work [name="__RequestVerificationToken"]. Basically what I am doing here, is tricking the page into thinking I clicked a button and then telling it which function to look at. Additionally, you have access to all your model fields so you do not need to pass them.

Here is the select list:

   <div class="col-md-2"><select id="ddlPortalName" asp-for="selectedPortalName" asp-items="Model.portalNames" onchange="ConcatenateURL();"></select></div> 

And then here is the JS function, notice I had to change the form action to tell it which page function to look at.

<script type="text/javascript">
    function ConcatenateURL() {         
        document.forms[0].action = "VisibilityTest?handler=ConcatURL";
        document.forms[0].submit();
    }
</script>

And then finally here is the c# file method.

   public void OnPostConcatURL()