【问题标题】:Calling C# method from javascript in MVC4在 MVC4 中从 javascript 调用 C# 方法
【发布时间】:2014-03-27 11:38:05
【问题描述】:

我正在尝试从 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;
}

谢谢。

【问题讨论】:

  • 错误是什么?哪里出了问题?
  • 什么也没发生,它没有显示任何错误信息。
  • 好的。 AJAX 方法是否被调用?
  • 不要传递“IndexController”,而是只传递“Index”
  • @Vinicius 是的。你的 AJAX 调用发生了吗?

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


【解决方案1】:

在 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 中使用 url 路由

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 2013-11-23
    • 2014-03-22
    • 2012-03-06
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    相关资源
    最近更新 更多