如何通过选择下拉列表来填充带有json数据的文本框

时间:2014-04-18 05:52:12

标签: c# asp.net json asp.net-web-api

`public partial class DropDownApi:System.Web.UI.Page     {          string _URL =“/ api / Insurance”;

    protected void Page_Load(object sender, EventArgs e)
    {
            WebRequest req = WebRequest.Create(_URL);
            req.Method = "GET";
            // req.Headers.Add("key");
            req.ContentType = "application/json; charset=utf-8";
            WebResponse resp = req.GetResponse();
            Stream stream = resp.GetResponseStream();
            StreamReader re = new StreamReader(stream);
            String json = re.ReadToEnd();
            json = "{\"InsuranceDetails\":" + json + "}";
            wrapper w = (wrapper)new JavaScriptSerializer().Deserialize(json, typeof(wrapper));


            ddlinsurance.DataSource = w.InsuranceDetails;
            ddlinsurance.DataBind();
        }
        public class wrapper
        {
            public List<insurance_master> InsuranceDetails { get; set; }
        }`<asp:DropDownList ID="ddlinsurance" runat="server" AutoPostBack="false" DataTextField="policy_number"></asp:DropDownList>`

`我的下拉列表中填充了json数据(policy_number),现在当我从下拉列表中选择policy_number时,它必须通过匹配所选的policy_number来显示文本框中的剩余详细信息。我已经为我的项目使用了MVC WebApi服务。 任何人都可以帮助我!!!

先谢谢。

1 个答案:

答案 0 :(得分:0)

这不是答案,但我认为这会对你有帮助..

HTML

<select id="list">
     <option value="">Choose</option>
</select>
<input type="text" id="inp" />

的JavaScript

// sample json data
var sampleJson = [
    { 'policy_number': 1, 'data': 'policy 1', 'display': 'one' },
    { 'policy_number': 2, 'data': 'policy 2', 'display': 'two' },
    { 'policy_number': 3, 'data': 'policy 3', 'display': 'three' }
];

//get select element using id
var select = document.getElementById('list');

//append option to select list with values from sampleJson
for (var i = 0; i < sampleJson.length; i++) {
    var option = document.createElement("option");
    option.value = sampleJson[i]['policy_number'];
    option.text = sampleJson[i]['display'];
    select.appendChild(option);
}          
var input = document.getElementById('inp');

//onchange event handler for select 
select.onchange = function()
{
    for (var i = 0; i < sampleJson.length; i++) {
        //selecetd value present in sampleJson set it into textbox
        if(sampleJson[i]['policy_number'] == this.value)
        {
            input.value = sampleJson[i]['data'];
        }
        // check the value is not empty(for default Choose option)
        if(this.value == '')
        {
            input.value = this.value;
        }
    }
};

以下是 Demo