在 mvc 中使用 webservice 填充下拉列表 [英] fill dropdownlist using webservice in mvc

查看:29
本文介绍了在 mvc 中使用 webservice 填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 webservice 填充下拉列表,并想使用 ajax 将选定的值传递给控制器​​,我该怎么做,请帮助这是我迄今为止尝试过的.这里是我的 webservice 中的内容是 json 格式.假设这是我的网络服务 https://www.abc.com/webservices/radius.php?json

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"
        }, ]
}

我在尝试什么

$.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>

控制器

[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

推荐答案

创建下拉列表:

<select name="MySelect" id="MySelect">

</select>

现在在 javascript 中,也使用 jquery:

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

使用 $.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");

            }
       });

这里DEMO FIDDLE 用于使用 javascript 填充选项.

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

这篇关于在 mvc 中使用 webservice 填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆