3.输入商品名称后自动弹出其价格示例

1.创建数据表,设定商品名称和其价格,如下图:

  

2.创建强数据集

  

并增加GetDataByName方法,是用来根据商品名称来查询其对应的价格。

SELECT ID, Name, price FROM dbo.T_ProductPrice where Name=@Name

3.创建服务端,用来查询商品价格

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using 输入商品名自动弹出价格.DataSetProductPriceTableAdapters;

namespace 输入商品名自动弹出价格
{
    /// <summary>
    /// GetPrice 的摘要说明
    /// </summary>
    public class GetPrice : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string name=context.Request["name"];
            var datatable= new T_ProductPriceTableAdapter().GetDataByName(name);
            if (datatable.Count <= 0)
            {
                context.Response.Write("wrong|没有数据。");
            }
            else
            {
                decimal price = datatable.Single().price;
                context.Response.Write("ok|" + price);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

4.创建客户端,加上jQuery库,html源码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="js/jquery-1.10.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#Select1").change(function () {
                var name = $("#Select1 option:selected").text();
               
                $.post("GetPrice.ashx", { "name": name }, function (data, status) {
                    if (status == "success") {
                        var arrs = data.split("|");
                        if (arrs[0] == "wrong")
                            alert(arrs[1]);
                        else if (arrs[0] == "ok")
                            $("#txtprice").val(arrs[1]);
                        else {
                            alert("返回数据格式错误");
                        }

                    }
                    else
                        alert("AJAX出错.");
                });
            });
        });
    </script>
</head>
<body>

    <select id="Select1" name="D1">
        <option  >台式电脑</option>
        <option >笔记本</option>
        <option >QQ轿车</option>
        <option >苹果电脑</option>
        <option >苹果手机</option>
        <option >灯泡</option>
    </select>
    <label for="txtprice">价格: </label>
   <input type="text" id="txtprice" />
</body>
</html>

5.运行截图

 

原文地址:https://www.cnblogs.com/yagzh2000/p/3173401.html