在MVC4中从javascript调用C#方法

时间:2014-03-27 11:38:06

标签: c# javascript asp.net-mvc-4 methods

我尝试从javascript调用c#方法,但没有任何效果。这要做的是我在用户按回车后调用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;
}

感谢。

1 个答案:

答案 0 :(得分:0)

在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

中使用网址路由