[英]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.
我知道我必须使用 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);
});
});
});
I'm fairly new to MVC so apologies if this is very simple!我对MVC相当陌生,如果这很简单,我很抱歉!
Thanks谢谢
try this work around试试这个解决办法
var enteredCity = $('#city').val(); var enterCity = $('#city').val();
$.get("@Url.Action("GetWeather","Home")"+"?City="+enteredCity, function (response) {
@Url.Action is server-side, whereas javascript is client-side. @Url.Action 是服务器端,而 javascript 是客户端。
So you cannot change a server-side element (eg @Url.Action) with javascript, you'll have to use a form.因此,您不能使用 javascript 更改服务器端元素(例如 @Url.Action),您必须使用表单。
$.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. ajax 调用通常有一个 data 属性。你可以使用它来设置你的查询字符串值。 $.get(url, data, function)
$.get(url, 数据, 函数)
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.另一种可能更有意义的方法是使用完整的 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.