繁体   English   中英

从MVC4中的JavaScript调用C#方法

[英]Calling C# method from javascript in MVC4

我正在尝试从javascript调用ac#方法,但没有任何效果。 这要做的是,我在用户按Enter键后调用javascript,然后在c#中调用方法,API尝试查找城市,然后显示他键入的城市的温度。 但是我尝试了很多事情,但是没有任何效果。

编码:

我的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';
                }
            });

        }
    }

我正在尝试调用的C#方法:

[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;
}

谢谢。

将断点放在getWeather()函数中,然后尝试以下操作:

[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;
}

并检查您是否在global.asax中使用网址路由

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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