简体   繁体   中英

Calling C# method from javascript in MVC4

i'm trying to call ac# method from javascript but nothing works. What this have to do is that i call the javascript after user press enter, then i call the method in c#, the API try to find the city, then i show the temperature of the city that he typed. But i tried a lot of thing, but nothing worked.

the code:

My JavaScript:

function enterpressalert(e, textarea) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            var tb = $('#search-bar').val();

            $.ajax({
                url: '@Url.Action("getWeather", "IndexController")',
                type: 'GET',
                dataType: 'text',
                // we set cache: false because GET requests are often cached by browsers
                // IE is particularly aggressive in that respect
                cache: false,
                data: { city: tb },
                success: function () {
                    $('#search-bar').val() = 'funcionou';
                }
            });

        }
    }

My c# method that i'm trying to call:

[WebMethod]
public LocalWeather getWeather(string city)
{
    LocalWeatherInput input = new LocalWeatherInput();

    input.query = city;
    input.num_of_days = "5";
    input.format = "JSON";

    FreeAPI api = new FreeAPI();
    LocalWeather localWeather = api.GetLocalWeather(input);

    return localWeather;
}

thanks.

Place a break point in getWeather() function and try this:

[HttpGet]
public LocalWeather getWeather(string city)
{
    LocalWeatherInput input = new LocalWeatherInput();

    input.query = city;
    input.num_of_days = "5";
    input.format = "JSON";

    FreeAPI api = new FreeAPI();
    LocalWeather localWeather = api.GetLocalWeather(input);

    return localWeather;
}

and also check whether your are using url routing in global.asax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM