问题
i want to fill the dropdown using webservice and want to pass the selected value to the controller using ajax how can i do that please help here is what i have tried so far. here are the contents which is in my webservice is in json format. suppose this is my webservice https://www.abc.com/webservices/radius.php?json
{
"results" : [{
"zip" : "12345",
"city" : "delhi",
"distance" : "0.0"
}, {
"zip" : "123456",
"city" : "noida",
"distance" : "3.1"
}, {
"zip" : "123457",
"city" : "faridabad",
"distance" : "9.1"
}, ]
}
what i was trying
$.getJSON('https://www.abc.com/webservices/radius.php?json',function(results){
for (var i = 0; i <= s.results.length - 1; i++) {
var x = new Option();
x.text = s.results[i].city;
x.value = s.results[i].zip;
console.log(x);
document.getElementById('dd').appendChild(x);
}
})
<select id='dd'>
</select>
Controller
[HttpPost]
public ActionResult Search(string distance)
{
//stuffs
}
please help how to call that webservice and fill that dropdown and how to pass it to the controller
回答1:
Create a dropdown :
<select name="MySelect" id="MySelect">
</select>
now in javascript, using jquery as well:
var Options = "";
$.getJSON('https://www.abc.com/webservices/radius.php?json', function (response) {
for (var i = 0; i < response.results.length; i++) {
Options += "<option value '" + response.results[i].zip + "'>" + response.results[i].city + "</option>";
}
});
$("#MySelect").append(Options); // appending all options here
using $.ajax :
var Options = "";
$.ajax({
url: "https://www.abc.com/webservices/radius.php?json",
type: "get",
success: function (response) {
for (var i = 0; i < response.results.length; i++) {
Options += "<option value '" + response.results[i].zip + "'>" + response.results[i].city + "</option>";
}
},
error: function () {
alert("failure");
}
});
Here is DEMO FIDDLE for populating options with javascript.
Now in Action you can get its value this way:
[HttpPost]
public ActionResult Search(FormCollection form)
{
string ddlValue = form["MySelect"].ToString();
}
来源:https://stackoverflow.com/questions/27778945/fill-dropdownlist-using-webservice-in-mvc