DinnerNow.Net中的AJAX应用体味(2)

继续上一篇,接下来让我们看一下,DinnerNowsearch.aspx文件的源代码

 

Code<%@ Page Language="C#" MasterPageFile="Main.master" AutoEventWireup="true" Inherits="Search"
  2    Title="DinnerNow.net" CodeBehind="Search.aspx.cs" 
%>
  3<%@ Register Src="LoginControl.ascx" TagName="LoginControl" TagPrefix="uc2" %>
  4<%@ Register Src="SearchBar.ascx" TagName="SearchBar" TagPrefix="uc1" %>
  5<asp:Content ID="Content1" ContentPlaceHolderID="LoginPlaceHolder" runat="Server">
  6    <uc2:LoginControl ID="LoginControl1" runat="server"></uc2:LoginControl>
  7</asp:Content>
  8<asp:Content ID="SearchBarContent" ContentPlaceHolderID="SearchBarPlaceHolder" runat="Server">
  9    <uc1:SearchBar ID="SearchBar1" runat="server"></uc1:SearchBar>
 10</asp:Content>
 11<asp:Content ID="Content3" ContentPlaceHolderID="MainContentPlaceHolder" runat="Server">
 12    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
 13        <Services>
 14            <asp:ServiceReference Path="~/Services/ShoppingCartService.svc" />
 15        </Services>
 16    </asp:ScriptManagerProxy>
 17
 18
 19    <script type="text/javascript">
 20        //这个函数是用来处理回传信息的,这个是asp.net ajax框架里面的pageload(),在页面加载的时候自动运行
 21        function pageLoad()
 22        {
 23            try
 24            {
 25                //定义一个对象
 26                var PARAMETERS = {};
 27                //这是一种在JavaScript语言中定义函数的方法,函数名就是PARMETERS.load,在下面有调用,这里不运行
 28                PARAMETERS.load = function() {
 29                    PARAMETERS.map = {};
 30                    //这里表示提出请求的url地址,并且按照正则表达式将url进行替换,从形式上看,应该只是把传参的标记等等替换点,
 31                    //把前面正则表达式获取的值作为参数传给后面的function中的参数,这里有很强的对应关系,是根据searchbar.ascx里面的程序对应的
 32                    //[^&=],表示匹配除&=之外的任何字符
 33                    window.location.search.substring(1).replace(/([^&=]+)([=]([^&]*))?(&|$)/g,function(s,k,q,v){
 34                        if (undefined === PARAMETERS.map[k]) {
 35                            PARAMETERS.map[k] = [];
 36                        }

 37                        PARAMETERS.map[k].push(decodeURIComponent(v));
 38                    }
);
 39                    for (var k in PARAMETERS.map) {
 40                        var a = PARAMETERS.map[k];
 41                        PARAMETERS.map[k] = ((1 == a.length) ? a[0] : a);
 42                    }

 43                }
;
 44                //刚刚定义的函数的调用
 45                PARAMETERS.load();
 46                //下面这个命令也是在searchbar.ascx里面写的JavaScript程序               
 47                set_Content(PARAMETERS.map.DeadLine, PARAMETERS.map.MenuType, PARAMETERS.map.PostalCode, PARAMETERS.map.RestaurantCategory);                        
 48                
 49                var service = new DinnerNow.Services.IMenuSearchService();
 50                service.FindRestaurant(PARAMETERS.map.PostalCode, PARAMETERS.map.MenuType, PARAMETERS.map.RestaurantCategory, PARAMETERS.map.DeadLine, onRestaurantSeachSuccess, onRestaurantSeachFailed, null);
 51            }

 52            catch(ex)
 53            {
 54                alert(ex);
 55                alert("对象无法被序列化");
 56            }

 57        }

 58        //感觉更应该理解为是种枚举类型
 59        var _divs = ["SearchResultsDivision","MenuDivision"];
 60        function DisplayDiv(divName)
 61        {
 62            //根据赋予的divName来进行决定谁显示,谁不显示,为了保证程序的健壮性所以采用了,每次都循环扫描的方法,上面的_divs代表一共有几个受影响
 63            for (var i=0; i <_divs.length; i++)
 64            {
 65                document.getElementById(_divs[i]).style.display = 
 66                    (_divs[i]==divName) ? "block""none";
 67            }

 68        }

 69        //ajax应用的成功回调函数
 70        function onRestaurantSeachSuccess(searchResult)
 71        {
 72            var restaurantContainer = document.getElementById("restaurantList");
 73            restaurantContainer.innerHTML = "";
 74            //这里是根据后端传过来的数据格式进行用JavaScript重写,写出一个resultslist
 75            for (var i=0; i<searchResult.length; i++)
 76            {
 77                var restaurantHtml= "<a href=""javascript:restaurantSelection_Click('"
 78                        + searchResult[i].RestaurantId + "''"
 79                        + searchResult[i].LogoImageLocation +"''"
 80                        + searchResult[i].Name +"');""><img src="""
 81                        + searchResult[i].LogoImageLocation + """ alt="""
 82                        + searchResult[i].Name + """ width=""154"" height=""90"" class=""thingreenline"" /></a>";
 83                var restaurantElement=document.createElement("span");
 84                restaurantElement.innerHTML = restaurantHtml;
 85                //每次循环都会新增一个span。即是饭店的logo
 86                restaurantContainer.appendChild(restaurantElement);
 87            }

 88            
 89           DisplayDiv("SearchResultsDivision");
 90        }

 91        
 92        function onRestaurantSeachFailed(result)
 93        {
 94            alert(result._message);
 95            alert("搜索失败");
 96        }

 97
 98            function restaurantSelection_Click(identifier, logo, name)
 99            {
100                /********** RestaurantSelected ***********/
101                document.getElementById("restaurantImage").src = logo;
102                document.getElementById("restaurantName").innerHTML = name;
103                //这里的restaurantDescription是有问题的,所有的饭店都是相同的描述,这里应该模仿下面的操作,也用wcf操作
104                document.getElementById("restaurantDescription").innerHTML = "Since 1923, the offering fas, friendly and courteous service.  We use only the best ingredients and maintain a skilled staff to answer your questions.  We have built our reputation on our commitment to providing quality service, which has earned us many valuable customers.";
105                //获取饭店菜单
106                document.getElementById("restaurantMenuFeed").href = "service/syndication.svc/rss/restaurants/"+ name;
107               
108                var restaurant = document.getElementById("restaurantID");//这是一个span,里面放的当前选中的restaurantidentifier
109                restaurant.innerHTML = identifier; //存放restaurantidentifier的过程
110                /********** RestaurantSelected ***********/
111                //这里进行了wcf调用
112                var service = new DinnerNow.Services.IMenuSearchService();
113                //这个return_MenuType()是在searchbar.ascx中写的JavaScript命令,当时没有用到,但却在这里用到了。
114                var menuType = return_MenuType();
115                var selectedMenuType = document.getElementById("selectedMenuItemCategory");//也是一个hidden控件,放着当前选的菜单项的分类,如breakfast等等
116                selectedMenuType.value = menuType;
117                //真正调用wcf的地方,这个是由scriptmanagerproxy自动写的代理程序
118                service.GetMenuItemsForMenu(identifier,menuType,restaurantSelection_onSuccess,restaurantSelection_onFailed,null);
119                service.GetMenuTypes(getMenuTypes_onSuccess, getMenuTypes_onFailed, null);
120            }

121            function ChangeMenuType(menuType)
122            {
123                var service = new DinnerNow.Services.IMenuSearchService();
124                //这里用到前面的赋值,感觉思路其实和viewstate一样,或者说viewstate是由这种思路得到启发的。
125                var identifier = document.getElementById("restaurantID").innerHTML;
126                var selectedMenuType = document.getElementById("selectedMenuItemCategory");
127                selectedMenuType.value = menuType;//改变标记,始终让他代表当前选中的餐类型
128                //我距地笑面的命令完全就可以等同的认为是中显示功能
129                service.GetMenuItemsForMenu(identifier,menuType,restaurantSelection_onSuccess,restaurantSelection_onFailed,null);
130                service.GetMenuTypes(getMenuTypes_onSuccess, getMenuTypes_onFailed, null);
131            }

132            function getMenuTypes_onSuccess(result)
133            {
134                var menuTypeContainer = document.getElementById("menuTypeListTab");//这里的tab不是控件而是纯粹用div做出来的,在div里面加了span
135                menuTypeContainer.innerHTML="";
136                var savedMenuType = document.getElementById("selectedMenuItemCategory");
137                var currentMenuType = savedMenuType.value 
138                
139                for (var i=0; i<result.length;i++)
140                {
141                    var menuType = result[i];
142                    //配置不同的css样式以达到显示出已被选中或者未被选中的目的
143                    var classStyle = "tabUnselected";
144                    if (menuType.MenuTypeName == currentMenuType)
145                    {
146                        classStyle = "tabSelected";
147                    }

148                    //利用字符串拼接来构造出一个由span组成的tab
149                    var menuTypeHtml = "<a class='" + classStyle + "' href=javascript:ChangeMenuType('" + menuType.MenuTypeName + "');>"
150                                     + "<span>" + menuType.MenuTypeName + "</span></a>";
151                    //创建一个span,把刚才的字符串写到其中,构造出tab                     
152                    var menuItemTypeElement=document.createElement("span");
153                    menuItemTypeElement.innerHTML = menuTypeHtml;
154                    //并且给他部署它应该在的位置         
155                    menuTypeContainer.appendChild(menuItemTypeElement);                                               
156                }

157            }

158            function getMenuTypes_onFailed(result)
159            {
160                var menuTypeList = $get("menuType");
161                menuTypeList.innerHTML="Failed Search";
162            }

163                
164            function restaurantSelection_onSuccess(result)
165            {
166                var menuItemContainer = document.getElementById("menuList");
167                menuItemContainer.innerHTML = "";
168                
169                /******** MenuItems **********/            
170                for (var i=0; i<result.length; i++)
171                {
172                    var menuItem = result[i];
173                    //给每个菜做了一个table,然后通过建立一个span加载,注意这里的图片显示是用img来做到的,menuitem的图片都存在该项目的images文件夹中
174                    //第二行写了个href,表示点击image在新窗口打开,查看大图,这些都是通过css实现的,JavaScript和c#代码做到的仅仅是提供了图片
175                    var menuItemHtml = "<table width='100%' border='0' align='center' cellpadding='8' cellspacing='0' class='thinblueline'><tr><td width='150' align='center' valign='top'><div class='hoverarea'><div><a href="""
176                            + menuItem.ImageLocation + """ target='_blank'> <img id=""MenuItemImage"" src="""
177                            + menuItem.ImageLocation + """ alt="""
178                            + menuItem.Name +"""/><img id=""Img1"" src="""
179                            + menuItem.ImageLocation+ """ alt="""
180                            + menuItem.Name+""" class=""hoverimage_preview""/></a></div></div></td><td valign='top'><strong>Item # "
181                            + i + "</strong><br/><strong>"
182                            + menuItem.Name+"</strong><br/>"
183                            + menuItem.Description+"<br/><br/><div align='left'><strong>Estimated Delivery Time: "
184                            + menuItem.PreparationTime+" minutes</strong></div></td><td width='80' align='right' valign='top'><strong>$"
185                            + menuItem.Price+"</strong><br/><br/><a class=""noUnderline"" href=""javascript:AddItemToShoppingCart('"
186                            + menuItem.Description + "''"
187                            + menuItem.ImageLocation + "''"
188                            + menuItem.MenuId + "''"
189                            + menuItem.MenuItemId + "''"
190                            + menuItem.Name + "''"
191                            + menuItem.PreparationTime + "''"
192                            + menuItem.Price + "');""><img src=""images/selectbutton.gif"" border=""0"" /></a></td></tr></table>";
193                            
194                    /*var menuItemHtml= "<table><tr><td align='center' valign='middle'><a href=""javascript:AddItemToShoppingCart('"
195                            + menuItem.MenuItemId + "');""><img src="""
196                            + menuItem.ImageLocation + """ alt="""
197                            + menuItem.Name + """ width=""154"" height=""90"" class=""thingreenline"" /></a></td></tr></table>";*/
198                    
199                    var menuItemElement=document.createElement("span");
200                    menuItemElement.innerHTML = menuItemHtml;
201                
202                    menuItemContainer.appendChild(menuItemElement);
203                }

204                /******** MenuItems **********/
205                //当一旦生成了菜谱后,购物车的抬头就被生成了,这里的生成也就是显示,通过下面一句
206                DisplayDivContent4("shoppingCart");
207                DisplayDiv("MenuDivision");
208            }

209            function restaurantSelection_onFailed(result)
210            {
211                alert("选择失败");
212            }

213            
214            function returnToRestaurantList_Click()
215            {
216                DisplayDivContent4("");
217                DisplayDiv("SearchResultsDivision");
218            }

219            
220           
221            
222            var menuSort =-1;//这个是排序的方法,在函数中有定义
223            //这个程序里面的参数都是在动态生成具体的菜的时候就写好的
224            function AddItemToShoppingCart(description,imageLocation,menuId,menuItemId,name,preparationTime,price)
225            {
226                var menuItem = new DinnerNow.Business.Data.RestaurantMenuItem();
227
228                menuItem.Description = description;
229                menuItem.ImageLocation = imageLocation;
230                menuItem.MenuId = menuId;
231                menuItem.MenuItemId = menuItemId;
232                menuItem.Name = name;
233                menuItem.PreparationTime = preparationTime;
234                menuItem.Price = price;
235                //以上是根据wcf规定的的datacontract定义并且赋值了变量
236                var restaurant = new DinnerNow.Business.Data.RestaurantHeader();
237                
238                restaurant.RestaurantId = document.getElementById("restaurantID").innerHTML;
239                restaurant.Name = document.getElementById("restaurantName").innerHTML;
240                restaurant.LogoImageLocation = document.getElementById("restaurantImage").src;
241                //以上是根据wcf规定的的datacontract定义并且赋值了变量
242               
243                DinnerNow.ShoppingCartService.AddItem(menuItem,restaurant,menuSort,addItemToShoppingCart_onSuccess,addItemToShoppingCart_onFailed,null);
244            }

245            
246            function addItemToShoppingCart_onSuccess(result)
247            {
248            
249                _refreshShoppingCart(result);
250            }

251            
252            function addItemToShoppingCart_onFailed(result)
253            {
254                alert("该菜目无法加入您的菜单");
255            }

256            //显示总价和预计送达时间的功能
257            function getTotals_onSuccess(result)
258            {
259                var shoppingCartTotalContainer = document.getElementById("shoppingCartTotals");
260                shoppingCartTotalContainer.innerHTML = "";
261                
262                var checkout ="";
263                if (result[0!= "$0.00")
264                     checkout = "Checkout.aspx";
265                
266                var shoppingCartTotalHtml = "<table width='100%' border='0' cellspacing='2' cellpadding='4'><tr><td width='22%' align='right' class='boldWhite'>Total:</td><td id='Td1' width='78%' class='boldWhite'>"
267                + result[0+ "</td></tr><tr><td align='right' class='boldWhite'>ETA:</td><td class='bodyTextWhite'>"
268                + result[1+ "</td></tr><tr><td>&nbsp;</td><td align='right'><a id='itemListCheckoutButton' href='"
269                + checkout + "'><img src='images/Checkoutbutton.gif' border='0'/></a></td></tr></table>";
270
271                var shoppingCartTotal=document.createElement("span");
272                shoppingCartTotal.innerHTML = shoppingCartTotalHtml;
273                
274                shoppingCartTotalContainer.appendChild(shoppingCartTotal);
275            }

276            
277            function getTotals_onFailed(result)
278            {
279                alert("无法获得总价");
280            }

281            
282            function DeleteItemFromShoppingCart(itemIdentifier)
283            {
284                DinnerNow.ShoppingCartService.RemoveItem(itemIdentifier,menuSort,deleteItemFromShoppingCart_onSuccess,deleteItemFromShoppingCart_onFailed,null);
285            }

286            
287            function deleteItemFromShoppingCart_onSuccess(result)
288            {
289                _refreshShoppingCart(result);
290            }

291            
292            function deleteItemFromShoppingCart_onFailed(result)
293            {
294                alert("菜单无法被删除");
295            }

296            
297            function refreshShoppingCart()
298            {
299                //根据判断选择的值是多少来,赋予menusort的值,再决定排序
300                menuSort = parseInt(document.getElementById ("menuSortOptionList").value);
301                DinnerNow.ShoppingCartService.RefreshItems(menuSort,refreshShoppingCart_onSuccess,refreshShoppingCart_onFailed,null);
302            }

303            
304            function refreshShoppingCart_onSuccess(result)
305            {
306                _refreshShoppingCart(result);
307            }

308            
309            function refreshShoppingCart_onFailed(result)
310            {
311                alert("无法刷新菜单");
312            }

313            //这个是刷新购物车成功时候的操作
314            function _refreshShoppingCart(result)
315            {
316            
317                var shoppingCartContainer = document.getElementById("shoppingCartList");
318                shoppingCartContainer.innerHTML = "";
319                
320                var restaurantId = "";
321                var firsth = true;
322                
323                var html = "";
324
325                /******** Shopping Cart Items **********/
326                for (var i=0; i<result.length; i++)
327                {
328                    var shoppingCartItem = result[i];
329                    var subtotal = (shoppingCartItem.Price * shoppingCartItem.Quantity);
330
331                    var restaurantItemHtml="";
332                    var endPrevRestaurantItemHtml ="";
333                    //饭店名称抬头生成
334                    if (restaurantId != shoppingCartItem.RestaurantIdentifier && menuSort != 1)
335                    {
336                        if (!firsth)
337                            endPrevRestaurantItemHtml = "</table></td></tr>";
338                        
339                        firsth = false
340                        //这个restaurantId没有什么太大的作用仅仅用来判断是否有必要生成抬头,在if()中
341                        restaurantId = shoppingCartItem.RestaurantIdentifier;
342                        restaurantItemHtml = "<table width='100%' border='0' align='center' cellpadding='4' cellspacing='4' bgcolor='#5686B4' class='thinblueline'><tr><td align='left' bgcolor='#31465B' class='boldWhite'>"
343                                + shoppingCartItem.RestaurantName + "</td></tr><tr><td>";
344                    }

345                    //饭店所属的菜单实体生成
346                    var shoppingCartHtml = "<table width='100%' border='0' cellspacing='2' cellpadding='2' bgcolor='#5686B4'><tr><td align='left'><a class='noUnderline' href=""javascript:DeleteItemFromShoppingCart('"
347                            + shoppingCartItem.MenuItemIdentifier + "');""><img src='images/delete.gif' alt='移除' width='17' height='16'/></a></td><td align='left' width='60%'>"
348                            + shoppingCartItem.MenuItemName + "</td><td align='left'><input type='text' id='"
349                            + shoppingCartItem.MenuItemIdentifier + "_itemViewQuantityBox' size='2' class='checkOutFormsField' onchange=""updateShoppingCartQuantity('"
350                            + shoppingCartItem.MenuItemIdentifier + "');"" value ='"
351                            + shoppingCartItem.Quantity + "'></input></td><td align='left' nowrap='nowrap' class='bodyTextWhite'> $"
352                            + subtotal + "</td></tr>";
353                     
354                     html += endPrevRestaurantItemHtml+restaurantItemHtml+shoppingCartHtml+"</table><br/>";
355                }

356                /******** Shopping Cart Items **********/
357
358                if (html != "")
359                    html+="</td></tr></table>";
360                    
361                var shoppingCartElement=document.createElement("span");                   
362                shoppingCartElement.innerHTML = html;
363                
364                shoppingCartContainer.appendChild(shoppingCartElement);
365                //重新计算总价
366                DinnerNow.ShoppingCartService.Totals(getTotals_onSuccess, getTotals_onFailed,null);
367            }

368            //这个函数是在动态生成的代码中用到的
369            function updateShoppingCartQuantity(menuItemId)
370            {
371            
372                var newQuantity = parseInt(document.getElementById(menuItemId+"_itemViewQuantityBox").value);
373                DinnerNow.ShoppingCartService.UpdateQuantity(menuItemId, newQuantity, menuSort, updateShoppingCartQuantity_onSuccess, updateShoppingCartQuantity_onFailed,null);
374            }

375            
376            function updateShoppingCartQuantity_onSuccess(result)
377            {
378                _refreshShoppingCart(result);
379            }

380            
381            function updateShoppingCartQuantity_onFailed(result)
382            {
383                alert("无法改变所选菜目的数量");
384            }

385            
386            function SelectCurrentMenu()
387            {
388                // Raise a click event for a hidden link on this form, so we cause a post-back
389                ExecuteTrigger("currentMenuTrigger.ClientID");
390            }

391            
392            function SelectPreviousMenus()
393            {
394                // Raise a click event for a hidden link on this form, so we cause a post-back
395                ExecuteTrigger("previousOrdersTrigger.ClientID");
396            }

397           
398            
399    
</script>
400
401    <div id="SearchResultsDivision">
402        <!–style="display:none;">–>
403        <input id="selectedRestaurantIdentifier" type="hidden" runat="server" value="" />
404        <span id="restaurantID" style="display: none"></span>
405        <br />
406        <span class="boldDarkBlue">
407            <asp:Label runat="server" ID="searchResultsLabel" />
408        </span>
409        <br />
410        <br />
411        <!– Restaurant list goes here–>
412        <div id="restaurantList">
413        </div>
414    </div>
415    <div id="MenuDivision" style="display: none;">
416        <input id="selectedMenuItemCategory" type="hidden" value="" />
417        <input id="selectedMenuItem" type="hidden" runat="server" value="" />
418        <br />
419        <div id="restaurantSelected">
420            <div class="restaurantNavHeader">
421                <div class="restaurantNavHeaderLeft">
422                    <span class="boldBlue">Your Selected Restaurant Menu</span>
423                </div>
424                <div class="restaurantNavHeaderRight">
425                    <input name="backToList" type="button" class="formbuttonBlue" value="Back To Restaurant List"
426                        onclick="returnToRestaurantList_Click();" />
427                </div>
428            </div>
429            <br />
430            <div class="restaurantDescription">
431                <div class="restaurantDescriptionLeft">
432                    <span>
433                        <img id="restaurantImage" src="" width="154" height="90" alt="Restaurant Logo" /></span>
434                </div>
435                <div class="restaurantDescriptionRight">
436                    <span id="restaurantName" class="boldGreen"></span>
437                    <br />
438                    <span id="restaurantDescription"></span>
439                    <br />
440                    <br />
441                    <id='restaurantMenuFeed' href="">
442                        <img src='images/rss.gif' alt='RSS' align='middle' border='0' /></a>&nbsp; Receive
443                    updates to the menu
444                </div>
445            </div>
446        </div>
447        <br />
448        <!– Menu Type (lunch, breakfast etc) go here –>
449        <div id="menuTypeListTab" class="tabUnselected">
450        </div>
451        <!– Menu items list goes here–>
452        <div id="menuList">
453        </div>
454    </div>
455</asp:Content>
456<asp:Content ID="Content4" ContentPlaceHolderID="RightMenuPlaceHolder" runat="Server">
457
458    <script type="text/javascript">
459        var _divsCt4 = ["shoppingCart"];
460        function DisplayDivContent4(divName)
461        {
462            for (var i=0; i <_divsCt4.length; i++)//这里的length=1,就是数据的大小,但是应该可以有很多个,对于不同的饭店。。有点不明白
463            {
464                document.getElementById(_divsCt4[i]).style.display = 
465                    (_divsCt4[i]==divName) ? "block""none";
466            }

467        }

468    
</script>
469
470    <input type="hidden" id="selectedOrder" value="" runat="server" />
471    <div id="shoppingCart" class="cartDetailsBox">
472        <!–visible="false"–>
473        <div>
474            <span>Your Menu Today</span> <span>
475                <select id="menuSortOptionList" onchange="refreshShoppingCart();" visible="true">
476                    <option value="-1">Sort Menu By ——&gt;</option>
477                    <option value="0">Restaurant</option>
478                    <option value="1">Name</option>
479                </select></span>
480            <!– Shopping Cart list goes here–>
481            <div id="shoppingCartList">
482            </div>
483            <!– Shopping Cart totals goes here–>
484            <div id="shoppingCartTotals">
485            </div>
486            <div>
487            </div>
488        </div>
489    </div>
490</asp:Content>
491

 

这个页面包括了两个用户控件一个是loginControl,另一个是SearchBar。前者没有什么可以多说的,SearchBar控件在这里我们先进行简要的说明。下面是SearchBar.ascx的源代码。比较简单有很多讲解会在注释中进行说明

 

Code<%@ Control Language="C#" AutoEventWireup="true" Inherits="SearchBar" Codebehind="SearchBar.ascx.cs" %>
  2<!—这段下载需要使用到的WCF应用–>
  3<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
  4    <services>
  5        <asp:ServiceReference Path="~/service/MenuSearch.svc/ajax" />
  6    </services>
  7</asp:ScriptManagerProxy>
  8<!—这段下载需要使用到的WCF应用–>
  9<script type="text/javascript">
 10    function searchButton_Click()
 11    {   
 12        //获取页面中所填写的和所选的,就是PostalCode,MenuType等等
 13        var DeadLine = $get("<%= deadlineSelect.ClientID %>").value;
 14        if (DeadLine=="-1" || DeadLine==null)
 15        {
 16            DeadLine="90";
 17        }

 18        //上面就是对Within中的选择进行一个判断,没有选的则按照最长时间90min取。
 19        var MenuType = $get("<%= menuTypeList.ClientID %>").value.trim();
 20        var PostalCode = $get("<%= postalCodeTextBox.ClientID %>").value;
 21        var RestaurantCategory = $get("<%= restaurantCategoryList.ClientID %>").value;
 22        //上面这些都是为给搜索页面进行搜索提供数据依据而做的准备。这里用到了用户端控件的ClientID属性,这个属性非常的好用,能够获得将在页面自动生成的ID。
 23        var searchUrl = "search.aspx";
 24        var path = document.location.pathname.toLowerCase();
 25        var isInSearchAspx = path.length>=searchUrl.length && path.substr(path.length - searchUrl.length,searchUrl.length) == searchUrl;
 26        //上面的程序将当前地址和搜索地址进行比较,比较后的结果用于判断运行哪段程序。这里判断是通过判断字符串长度进行的,而不是针对内容本身的
 27        //下面的程序则表示当前页如果不是搜索页的时候运行,这里是跳转到搜索页的,发生QueryString传递。
 28        if (!isInSearchAspx)
 29        {
 30            var href = "search.aspx?PostalCode="+PostalCode+"&MenuType="+MenuType+"&RestaurantCategory="+RestaurantCategory+"&DeadLine="+DeadLine;
 31            document.location.href = href;
 32            
 33        }

 34        else//在搜索页时候运行的程序,这里不进行页面跳转,直接调用WCF服务,同时根据前面获取的数值,进行AJAX应用。具体的WCF使用基础这里就不多做介绍了。
 35        {
 36            var service = new DinnerNow.Services.IMenuSearchService();
 37            service.FindRestaurant(PostalCode, MenuType, RestaurantCategory, DeadLine, restaurantSearch_onSuccess, restaurantSearch_onFailed, null);
 38        }

 39        return false;
 40    }

 41    //当上面的WCF服务调用成功时的回调函数                   
 42    function restaurantSearch_onSuccess(result)
 43    {
 44        if (typeof(onRestaurantSeachSuccess)!="undefined")
 45        {
 46            onRestaurantSeachSuccess(result);
 47        }

 48    }

 49   //当上面的WCF服务调用失败时的回调函数                   
 50    function restaurantSearch_onFailed(result)
 51    {
 52        alert("搜索失败");
 53    }

 54//这个函数在这里并没有看到哪里使用,并且发现和执行搜索中的var MenuType = $get("<%= menuTypeList.ClientID %>").value.trim();的语句功能重复了。感觉是不是有点奇怪?
 55//其实我感觉也很奇怪,但奇怪的不是没有使用到,因为这个函数会在search.aspx中使用。
 56//我奇怪的是为什么在这里定义,另一个页面用,这点很迷惑,希望有大牛能告诉我下这么做的用以
 57    function return_MenuType()
 58    {
 59        return $get("<%= menuTypeList.ClientID %>").value;
 60    }

 61//这个同上面的解释
 62//同时这个函数很简单,就不多做说明了
 63    function set_Content(deadLine, menuType, postalCode, restaurantCategory)
 64    {
 65        /***************** DeadLine ********************/
 66        var deadLineList=$get("<%= deadlineSelect.ClientID %>");
 67        for(var i=0;i<deadLineList.options.length;i++)
 68        {
 69            var option = deadLineList.options[i];
 70            option.selected = option.value==deadLine;
 71        }

 72        /***************** DeadLine ********************/
 73        /***************** Menu Type ********************/
 74        var menuTypeList=$get("<%= menuTypeList.ClientID %>");
 75        for(var i=0;i<menuTypeList.options.length;i++)
 76        {
 77            var option = menuTypeList.options[i];
 78            option.selected = option.value==menuType;
 79        }

 80        /***************** Menu Type ********************/
 81        /***************** Postal Code ********************/
 82        var postalCodeTextBox=$get("<%= postalCodeTextBox.ClientID %>");
 83        postalCodeTextBox.value = postalCode;
 84        /***************** Postal Code ********************/        
 85        /***************** Restaurant Category ********************/
 86        var restaurantCategoryList=$get("<%= restaurantCategoryList.ClientID %>");
 87        for(var i=0;i<restaurantCategoryList.options.length;i++)
 88        {
 89            var option = restaurantCategoryList.options[i];
 90            option.selected = option.value==restaurantCategory;
 91        }

 92        /***************** Restaurant Category ********************/
 93    }

 94
</script>
 95<table width="100%" border="0" cellspacing="0" cellpadding="0">
 96    <tr>
 97        <td align="right" bgcolor="#ffffff">
 98            <table width="100%" border="0" cellpadding="0" cellspacing="0" background="images/bkg_selector.gif" class="thinblueline">
 99                <tr>
100                    <td width="20%" align="center">
101                        <table border="0" cellspacing="2" cellpadding="2">
102                            <tr>
103                                <td align="right" nowrap="nowrap" class="boldWhite">Your Zip</td>
104                                <td><input id="postalCodeTextBox" type="text" class="formfield" size="7" runat="server" /></td>
105                            </tr>
106                        </table>
107                    </td>
108                    <td width="2"><img src="images/selectordivider.gif" alt="divider" width="2" height="41" /></td>
109                    <td align="center">
110                        <table border="0" cellspacing="2" cellpadding="2">
111                            <tr>
112                                <td align="right" nowrap="nowrap" class="boldWhite">Food Type </td>
113                                <td align="left">
114                                    <asp:ObjectDataSource ID="RestaurantCategoryDataSource" runat="server" SelectMethod="SelectAll" TypeName="DinnerNow.RestaurantCategoryDataSource"/>
115                                    <asp:DropDownList ID="restaurantCategoryList" runat="server" 
116                                        DataSourceID="RestaurantCategoryDataSource" DataTextField="Description" 
117                                        DataValueField="RestaurantId"/>                        
118                                </td>
119                            </tr>
120                        </table>
121                    </td>
122                    <td width="2"><img src="images/selectordivider.gif" alt="divider" width="2" height="41" /></td>
123                    <td width="20%" align="center">
124                        <table border="0" cellspacing="2" cellpadding="2">
125                            <tr>
126                                <td align="right" class="boldWhite">Meal</td>
127                                <td align="left">
128                                    <asp:ObjectDataSource ID="MenuTypeDataSource" runat="server" SelectMethod="SelectAll" TypeName="DinnerNow.MenuTypeDataSource"/>
129                                    <asp:DropDownList ID="menuTypeList" runat="server" 
130                                        DataSourceID="MenuTypeDataSource" DataTextField="MenuTypeName" 
131                                        DataValueField="MenuTypeName" />                        
132                                </td>
133                            </tr>
134                        </table>
135                    </td>
136                    <td width="2"><img src="images/selectordivider.gif" alt="divider" width="2" height="41" /></td>
137                    <td width="20%" align="center">
138                        <table border="0" cellspacing="2" cellpadding="2">
139                            <tr>
140                                <td align="right" nowrap="nowrap" class="boldWhite">Within</td>
141                                <td align="left">
142                                    <asp:DropDownList ID="deadlineSelect" runat="server" >
143                                        <asp:ListItem Text="" Value="-1" />
144                                        <asp:ListItem Text="30 min." Value="30" />
145                                        <asp:ListItem Text="45 min." Value="45" />
146                                        <asp:ListItem Text="1 hour" Value="60" />
147                                        <asp:ListItem Text="90 min." Value="90" />
148                                    </asp:DropDownList>                        
149                                </td>
150                            </tr>
151                        </table>
152                    </td>
153                    <td width="2"><img src="images/selectordivider.gif" alt="divider" width="2" height="41" /></td>
154                    <td width="80" align="center" valign="middle">
155                        <table border="0" cellpadding="2" cellspacing="2">
156                            <tr>
157                                <td>    
158                                    <asp:ImageButton ID="searchButton" runat="server" ImageUrl="images/searchbutton.gif" BorderWidth="0" ImageAlign="AbsBottom" OnClick="searchButton_Click" OnClientClick="javascript:return searchButton_Click();" />
159                                </td>
160                            </tr>
161                        </table>
162                    </td>
163                </tr>
164            </table>
165        </td>
166    </tr>
167</table>
168

上面的Html语言也没有什么值得多说的。下面来看看SearchBar.aspx.cs文件中的代码。

 

 

Code
  2using System;
  3using System.Data;
  4using System.Configuration;
  5using System.Collections;
  6using System.Web;
  7using System.Web.Security;
  8using System.Web.UI;
  9using System.Web.UI.WebControls;
 10using System.Web.UI.WebControls.WebParts;
 11using System.Web.UI.HtmlControls;
 12using DinnerNow.Web.Views;
 13using DinnerNow.Web;
 14using DinnerNow;
 15
 16public partial class SearchBar : System.Web.UI.UserControl, ISearchBarView
 17{
 18    private SearchBarViewPresenter presenter;
 19
 20    protected void Page_Load(object sender, EventArgs e)
 21    {
 22        // Populate the search bar with the text from the last search.
 23        if (!this.IsPostBack)
 24        {
 25            //绑定DataSource
 26            this.DataBind();
 27            //下面的方法会将用户输入的搜索的条件显示出来
 28            presenter.OnViewInitialize();
 29        }

 30}

 31    protected void searchButton_Click(object sender, EventArgs e)
 32    {
 33        //这是根据设置的搜索条件进行搜索的,但是却没有用到。
 34        presenter.OnSearch(new SearchCriteria()
 35        {
 36            PostalCode = this.PostalCode,
 37            RestaurantCategory = new Guid(this.RestaurantCategory),
 38            MenuType = this.MenuType,
 39            Deadline = this.Deadline
 40        }
);
 41    }

 42
 43    public string RestaurantCategory
 44    {
 45        get
 46        {
 47            return this.restaurantCategoryList.SelectedValue;
 48        }

 49
 50        set
 51        {
 52            this.restaurantCategoryList.SelectedIndex = this.restaurantCategoryList.Items.IndexOf(this.restaurantCategoryList.Items.FindByValue(value.ToString()));
 53        }

 54    }

 55
 56    public string MenuType
 57    {
 58        get
 59        {
 60            return this.menuTypeList.SelectedValue;
 61
 62        }

 63
 64        set
 65        {
 66            this.menuTypeList.SelectedIndex = this.menuTypeList.Items.IndexOf(this.menuTypeList.Items.FindByValue(value));
 67        }

 68    }

 69
 70    public string PostalCode
 71    {
 72        get
 73        {
 74            return this.postalCodeTextBox.Value;
 75        }

 76
 77        set
 78        {
 79            this.postalCodeTextBox.Value = value;
 80        }

 81    }

 82
 83    public int Deadline
 84    {
 85        get
 86        {
 87            int result;
 88            if (int.TryParse(this.deadlineSelect.SelectedValue, out result))
 89            {
 90                return result;
 91            }

 92            return 0;
 93        }

 94
 95        set
 96        {
 97
 98            this.deadlineSelect.SelectedIndex = this.deadlineSelect.Items.IndexOf(this.deadlineSelect.Items.FindByValue(value.ToString()));
 99        }

100    }

101    //注意这里初始化了presenter
102    protected override void OnInit(EventArgs e)
103    {
104        base.OnInit(e);
105        presenter = new SearchBarViewPresenter(new SessionStateProvider(), new WebNavigationService());
106        presenter.View = this;
107    }

108    public void ShowCriteria(SearchCriteria criteria)
109    {
110        this.PostalCode = criteria.PostalCode;
111        this.Deadline = criteria.Deadline;
112        this.MenuType = criteria.MenuType.ToString();
113        this.RestaurantCategory = criteria.RestaurantCategory.ToString();
114    }

115}

116

 

上面的代码要说 起 来,又会引出来一大堆的知识,要完全理解上面的代码还需要对利用设计的很多接口进行分析,这部分内容我会在以后进行分析,在这里先姑且让我们专注于页面的 AJAX应用,对于上面的理解只要先按字面理解即可,比如presenter.OnViewInitialize();就理解为显示初始化即可。





 » 订阅本站:RSS订阅

发表评论

您也可以使用微博账号登陆

无觅相关文章插件,快速提升流量