【问题标题】:Passing Id from ashx page to aspx lable or hidden field将 ID 从 ashx 页面传递到 aspx 标签或隐藏字段
【发布时间】:2015-07-02 14:32:36
【问题描述】:

我有一个文本框,它是自动完成的文本框(即它绑定来自数据库的数据并相应地在按键时显示结果)

using (SqlCommand cmd = new SqlCommand())
{
   cmd.CommandText = "select (Patient_First_Name+' '+Patient_Last_Name+' '+Patient_DOB+' '+Patient_Home_Phone+' '+Patient_Account_No)as Patient_Name from PATIENT_DETAIL where " + "Patient_First_Name like @SearchText + '%' and Practice_Id in (select id from PRACTICE_DETAIL where practice_Name_Description = '" + st + "')";
   cmd.Parameters.AddWithValue("@SearchText", prefixText);
   cmd.Connection = conn;
   StringBuilder sb = new StringBuilder(); 
   conn.Open();
   using (SqlDataReader sdr = cmd.ExecuteReader())
   {
       while (sdr.Read())
       {
           sb.Append(sdr["Patient_Name"]).Append(Environment.NewLine);
       }
   }
   conn.Close();
   context.Response.Write(sb.ToString()); 
}

现在在我的表中,每一行都有 Id 列。每当我在文本框中选择任何结果时,我都想将该 ID 传输到我的标签或 aspx 页面中的隐藏字段。

我认为我需要在 "while(sdr.Read())" 块内进行一些更改,但不知道该怎么做。

谁能告诉我怎么做。

【问题讨论】:

  • 我假设您正在使用 ajax... 如果是这样,您的返回字符串可能是一个字典,其中 key=id value=textbpxValue。或者,您返回的字符串可能类似于 id#textboxValue。在您的客户端中,您必须通过 # 拆分字符串并将值添加到适当的元素。

标签: jquery asp.net ajax autocomplete ashx


【解决方案1】:

理想情况下,您应该使用 DTO 发送数据。步骤

首先创建一个帮助类

public class Patient
{
    public string PatientID { get; set; }
    public string PatientName { get; set; }
}

现在像这样更改你的 ashx 代码

var patients = new List<Patient>();
.....
.....
using (SqlCommand cmd = new SqlCommand())
{
    cmd.CommandText = "select Patient_ID, Pateient_Name from SomeTable";
    cmd.Connection = conn;
    StringBuilder sb = new StringBuilder();
    conn.Open();
    using (SqlDataReader sdr = cmd.ExecuteReader())
    {
        while (sdr.Read())
        {
            patients.Add(new Patient
            {
                PatientID = sdr["Patient_ID"].ToString(),
                PatientName = sdr["Patient_Name"].ToString()
            }); 
        }
    }
    conn.Close();
    var serializer = new JavaScriptSerializer();
    var outputJson = serializer.Serialize(patients);
    context.Response.Write(outputJson);
}

这将为您提供字符串输出

[{"PatientID":"1","PatientName":"blah"},{"PatientID":"2","PatientName":"blsdsdah"}]

现在您需要在 aspx 页面上反序列化。 (不确定您是在服务器端还是客户端需要它)

服务器端

var serializer = new JavaScriptSerializer();
var patients = serializer.Deserialize<List<Patient>>(op);

客户端

.done(function(){
    var patients = $.parseJSON( data );
    for(var i = 0; i< patients.length; i++){
        console.log(patients[i].PatientID + " : " + patients[i].PatientName);
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多