Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

c# asp.net mvc question

Hi,

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:

So if the user types the city 'London' for example. script code passes 'London' as a parameter. How can i achieve this?:

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

            });

        });

    });
</script>

Many thanks

1 Answer

Steven Parker
Steven Parker
231,248 Points

It's simple to get the value of the "city" input field inside the JS/jQuery event handler:

var city = $("#city").val();

But this value won't be present as the page is being constructed, so you would not be able to use it in the "Url.Action" helper method. You'll need to construct the URL using JavaScript instead.

Hi Steven,

I'm not entirely sure what you mean by constructing the URL.

Do you mean something like:

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

As in build the break the full Url.Action down into sub parts?

Steven Parker
Steven Parker
231,248 Points

It's more about when things happen. The "Url.Action" helper method happens inside the server, before the page is given to the browser. But the user doesn't input a value in the textbox until after the page is displayed in the browser.