Forum Discussion

panos2024b's avatar
panos2024b
Copper Contributor
Oct 28, 2024
Solved

ajax and connection to mvc .net

I need to access some c# code from javascript in MVC ,NET (not blazor). I have the below. This is very specific to .NET and MVC stack and not a generic ajax question like another one in stack overfow. I get no error message it just continues to the next statement after the ajax call. There could be 2 possible issues i think. My url: '/Home/CreatePostcodeFromCoordinates', is wrong. Or my C# assembly is not part of the assembly? or something similar. I am not that experienced with Web techs, I come from a DB background but can't be that difficult to get this link working right? Can't see anything else wrong. Also does the return value from C# need to be some special format or a string (as per now) is ok? this could be another reason? Thank you!

console.log("just before /Home/CreatePostcodeFromCoordinates");

$.ajax({
    type: "POST",
    url: '/Home/CreatePostcodeFromCoordinates',
    data: { param1: longitude, param2: latitude },
    success: function (response) {
        console.log('success');
        console.log(response);
    },
    error: function (error) { 
        console.error(error);
    }
});

 

  • It worked by this async: false,. However async: = false, is deprecated apparently soon and needs the new way which i will investigate and change in my code
    C#

    public string CreateCoordinatesFromPostcode(string postcode)
    {
    string result = "XXXXXX" // your logic
    return result;
    }
    JavaScript

    let result = '';
    $.ajax({
    type: "POST",
    url: '/clib/CreateCoordinatesFromPostcode',
    async: false,
    data: { postcode: postcode },
    success: function (response) {
    result = response;
    },
    error: function (error) {
    console.error(error);
    }
    });

    console.log("just after /clib/createCoordinatesFromPostcode");

    return result;

1 Reply

  • panos2024b's avatar
    panos2024b
    Copper Contributor
    It worked by this async: false,. However async: = false, is deprecated apparently soon and needs the new way which i will investigate and change in my code
    C#

    public string CreateCoordinatesFromPostcode(string postcode)
    {
    string result = "XXXXXX" // your logic
    return result;
    }
    JavaScript

    let result = '';
    $.ajax({
    type: "POST",
    url: '/clib/CreateCoordinatesFromPostcode',
    async: false,
    data: { postcode: postcode },
    success: function (response) {
    result = response;
    },
    error: function (error) {
    console.error(error);
    }
    });

    console.log("just after /clib/createCoordinatesFromPostcode");

    return result;

Resources