Lanshore Lanshore - 6 months ago 43
Ajax Question

Call a C# method from JavaScript Error

I am trying to call a c# method from javascript. I have a asp.net page which is parameteres.aspx, but at pressing the button it shows me an error 404.

This is the Method in parameters.aspx.cs

[WebMethod]
public void MethodSearch()
{


//Search
string _sEnrollmentEsiid;
string _sEnrollmentAddress;
string _sEnrollmentCity;
string _sEnrollmentZipCode;
//string _sAMS;


//_sEsiidText
GetDistributionPointsRequest disRequest = new GetDistributionPointsRequest();
_sEnrollmentEsiid = disRequest.EsiID;
_sEnrollmentAddress = disRequest.Address;
_sEnrollmentCity = disRequest.City;
_sEnrollmentZipCode = disRequest.Zip;


}


and this is the function in javascript:

<script type="text/javascript">
function testFunction() {
$.ajax({
type: "POST",
url: 'http://localhost:63788/parameters.aspx/MethodSearch',
//dataType: "json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>


and here how I call the function in HTML

<a href class="btn btn-danger" onclick="testFunction()">Test</a>
<label id="divResult"></label>


Can somebody tell me what am I doing wrong?
The error is: `Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Thanks in advance. `

Answer

In order to call a [WebMethod] on your page, the method must be marked as static. Of course you probably also want it do have a return value (given it's a search function) but I believe the lack of static is your specific problem. If there are other issues with your code, we can uncover them once it's possible to have your method called.

[WebMethod]
public static void MethodSearch()
{


    //Search
    string _sEnrollmentEsiid;
    string _sEnrollmentAddress;
    string _sEnrollmentCity;
    string _sEnrollmentZipCode;
    //string _sAMS;


    //_sEsiidText
    GetDistributionPointsRequest disRequest = new GetDistributionPointsRequest();
    _sEnrollmentEsiid = disRequest.EsiID;
    _sEnrollmentAddress = disRequest.Address;
    _sEnrollmentCity = disRequest.City;
    _sEnrollmentZipCode = disRequest.Zip;


}
Comments