简体   繁体   中英

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

I've created a basic weather forecast app. What im struggling to do is get the citys value from the input field, into my script. This is on my View:

So if the user types the city 'London' for example, script code passes 'London' as a parameter. How can i achieve this? I understand I must construct the URL using JavaScript but unsure how to.

     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);

            });

        });

    });

I'm fairly new to MVC so apologies if this is very simple!

Thanks

try this work around

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

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

@Url.Action is server-side, whereas javascript is client-side.

So you cannot change a server-side element (eg @Url.Action) with javascript, you'll have to use a form.

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

ajax calls usually have a data property.. you can use this to set your query string values. $.get(url, data, function)

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

another way that might make more sense would be to use the full ajax syntax.

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

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