无刷新绑定select数据源

王朝学院·作者佚名  2011-05-06  
宽屏版  字体: 小 | 中 | 大 | 超大  

这是利用Ajax、json给前台页面中的select绑定数据源,原理简单,诸君一看便知: 前台页面(asp.net):

前台页面 ASP.net

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UseJason.aspx.cs" Inherits="AjaxTest.UseJason" %>

<!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 runat="server">

<title></title>

<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>

<script type="text/Javascript">

$(document).ready(function () {

$("#btnGetCars").click(function () {

$.ajax({

type: "POST",

contentType: "application/json; charset=utf-8",

url: "UseJason.aspx/GetCars",

data: "{}",

dataType: "json",

success: GetCars,

error: function errorCallback(xmlhttpRequest, textStatus, errorThrown) {

alert(errorThrown + ":" + textStatus);

}

});

});

$("#SelectCars").change(function () {

CarSelectChange();

});

});

function GetCars(result) {

$(result.d).each(function () {

var o = document.createElement("option");

o.value = this['carName'];

o.text = this['carDescription'];

$("#SelectCars")[0].options.add(o);

});

}

function CarSelectChange() {

var o = $("#SelectCars")[0].options;

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<div>

<input type="button" id="btnGetCars" value="GetCars" />

<div style="margin-top: 20px">

<p>

Cars list :

</p>

<select id="SelectCars" style="width: 185px;">

</select>

<p>

PRice :

</p>

<input type="text" id="txtPrice" />

</div>

</div>

</div>

</form>

</body>

</html>

然后就是后台代码了(UseJason.aspx.cs)

后台(UseJason.aspx.cs)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Services;

namespace AjaxTest

{

public partial class UseJason : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

[WebMethod]

public static List<Car> GetCars()

{

List<Car> listCars = new List<Car>() {

new Car("A1","A1 Description",205000),

new Car("B12","B12 Description",105300),

new Car("Dfe","Dfe Description",658982),

new Car("Yfee","Yfee Description",8458700),

new Car("UUdde","UUdde Description",6548225)};

return listCars;

}

}

}

最后有一个类文件(Car.cs)

Car.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace AjaxTest

{

public class Car

{

public string carName { get; set; }

public string carDescription { get; set; }

public double carPrice { get; set; }

public Car(string name, string description, double price)

{

this.carName = name;

this.carDescription = description;

this.carPrice = price;

}

}

}

好了,本篇内容较简单,下一篇我们将讨论这个页面中的select的onchange事件……

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有