繁体   English   中英

c# asp.net mvc - 如何将参数传递到 Url.Action

[英]c# asp.net mvc - how to pass parameter into Url.Action

我创建了一个基本的天气预报应用程序。 我正在努力做的是从输入字段中获取城市值到我的脚本中。 这是我的看法:

因此,例如,如果用户键入城市“伦敦”,则脚本代码将“伦敦”作为参数传递。 我怎样才能做到这一点? 我知道我必须使用 JavaScript 构建 URL,但不确定如何构建。

     ViewBag.Title = "WeatherOrNot";
}

<h2>WeatherJS</h2>


<p id="reply"></p>
<p id="temp"></p>
<p id="humidity"></p>
<form>
   City:<br>
    <input id="city" type="text" name="city"><br>

</form>
<button>Get Weather</button>



<script>

    $(document).ready(function () {

        $("button").click(function () {
            $.get("@Url.Action("GetWeather","Home",new {City = "Mumbai" })", function (response) {
                //response
                $("#reply").text(response.name);
                $("#temp").text(response.main.temp);
                $("#humidity").text(response.main.humidity);

                //$("#city").get("city");
                console.log(response);

            });

        });

    });

我对MVC相当陌生,如果这很简单,我很抱歉!

谢谢

试试这个解决办法

var enterCity = $('#city').val();

$.get("@Url.Action("GetWeather","Home")"+"?City="+enteredCity, function (response) {

@Url.Action 是服务器端,而 javascript 是客户端。

因此,您不能使用 javascript 更改服务器端元素(例如 @Url.Action),您必须使用表单。

$.get("@Url.Action("GetWeather","Home")"+"?City=" + $("#city").val(), function (response)

ajax 调用通常有一个 data 属性。你可以使用它来设置你的查询字符串值。 $.get(url, 数据, 函数)

var city = $('#city').val();
$.get("@Url.Action("GetWeather","Home")", new {City = city}, function (response) {

另一种可能更有意义的方法是使用完整的 ajax 语法。

var city = $('#city').val();
$.ajax({
    url: "@Url.Action("GetWeather","Home")",
    data: {City: city},
    type: "GET"
}).done(function(response){
    $("#reply").text(response.name);
    $("#temp").text(response.main.temp);
    $("#humidity").text(response.main.humidity);
    //$("#city").get("city");
    console.log(response);
});

暂无
暂无

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

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