五一前后一直在忙安卓的東西,直到現在終於有機會喘口氣了,於是就抽空寫了這篇博文,來記錄我之前學習MVC一周后所寫的小例子:搜索淘寶商品並對商品進行價格篩選。
先上開始界面:
這個界面的源碼如下:
@{ ViewBag.Title = "主頁"; } <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { <fieldset> <legend>Search</legend> <div id ="editor-field"> <p>搜索商品 @Html.TextBox("keyword")</p> <p>價格上限 @Html.TextBox("max")</p> <p>價格下限 @Html.TextBox("min")</p> </div> </fieldset> <p> <input type="submit" value="Search" /> </p> }
值得注意的是我標為紅色的代碼,TextBox提供用戶輸入,並且提交用戶輸入,括號里的"keyword"是用來標識所提交的內容,方便我們從提交的表單中提取出用戶的輸入。
然后就是我們的主程序:
public class HomeController : Controller { string keyword; double max; double min; // // POST: /Index/ public ActionResult Index(FormCollection values) { keyword = values["keyword"]; if (values["max"] != null) { max = double.Parse(values["max"]); } if (values["min"] != null) { min = double.Parse(values["min"]); } if (keyword == null) { return View(); } else { List<Goods> goodsList = new List<Goods>(); GoodsInformation information = new GoodsInformation(keyword, max, min); List<string> imgs = information.getImg(); List<string> hrefs = information.getHref(); List<string> prices = information.getPrice(); for (int i = 0, len = prices.Count; i < len; i++) { Goods goods = new Goods(); goods.Imge = imgs.ElementAt(i); goods.href = hrefs.ElementAt(i ); goods.Name = keyword; goods.Price = double.Parse(prices.ElementAt(i)); goodsList.Add(goods); } return View("Search", "_Layout", goodsList); } } }
注意Index操作的參數,也就是我標為紅色的部分,它說明我們這個操作是提取所POST的表單並進行處理,所以最好注釋說明這是一個POST請求。
我們提交的表單其實就是鍵值對的集合,當然,我們在使用的時候,必須注意非空的判斷,因為用戶可能什么也沒輸入就提交了。這里我還沒有使用驗證,當用戶沒有輸入關鍵字,就會重新顯示搜索界面。如果用戶輸入相關信息並且提交,就會跳轉到另一個View---Search。
我們來輸入一些關鍵字吧!
看看我們的搜索結果是怎樣的:
抱歉,由於我沒有時間對顯示的界面進行排版,所以暫時無法提供完整的商品列表,只好截取出一部分出來。
嗯,MG 獨角獸還是相對較貴的。
Search的view的源碼如:
@model List<TaoBaoShop.Models.Goods> @{ ViewBag.Title = "搜索"; } <h3>搜索 @Model.ElementAt(0).Name 的結果列表:</h3> <ul> @foreach (var m in Model) { <li> <a href="@m.href"> <span><img alt="@m.Name" src="@m.Imge"/></span><br /> <span>總價:@m.Price</span></a><br /><br /> </li> } </ul>
我們在操作中傳遞一個模型給相應的視圖,然后就可以在視圖中使用該模型。
我們的商品列表的界面是根據價格進行排列的,這樣的實現並不難,只要在提取商品價格西信息的同時進行排序就可以了。
要想呈現商品列表,最主要的部分就是商品信息的提取:
string handleUrl(string content) { string strHtml = ""; WebResponse wrp = null; try { WebRequest wrq = WebRequest.Create(content); wrp = wrq.GetResponse(); } catch (WebException e) { throw e; } catch (Exception e) { throw e; } finally { if (wrp != null) { StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gbk")); strHtml += sr.ReadToEnd(); sr.Close(); wrp.Close(); } else { mIsLeft = false; } } return strHtml; }
得到淘寶網頁內容后,就是利用正則表達式對商品信息進行提取了。
例子非常簡單,還請各位見笑。