1. Razor Helpers 的運用:例如,定義好 ViewBag.Message = "Welcome to ASP.NET MVC!";我要在界面上顯示"Welcome ..."; 那我們一般有2種操作,3種實現操作:
2種操作:
Extension Method off HtmlHelpers 和 Razor Declarative @Helper Sytnax
3種實現方式:一、 Extension Method在當前項目下建立一個文件夾,命名為Helpers,在這個文件夾下添加 HtmlHelpers類,具體實現如下
namespaceMVCET.Helpers{publicstaticclassHtmlHelpers{publicstaticstringTruncat(thisHtmlHelperhelper,stringinput,intlength){if(input.Length<=length){returninput;}else{returninput.Substring(0,length)+"...";}}}}這時候,在頁面上只要添加這樣的代碼就可以顯示了:@using MVCET.Helpers<h2>@Html.Truncat(@ViewBag.Message as string,8)</h2>
二、 Razor Declarative @Helper Sytnax1. 在當前頁面添加如下代碼:@helper Truncat(string input, int length){ if(input.Length<=length) { @input } else { @input.Substring(0,length)<text>...(Razor)</text> }}再添加這行代碼:<h2>@Truncat(@ViewBag.Message as string, 8)</h2>
顯示的結果和上面的事一模一樣的。
2. 添加App_Code 文件夾,然后添加RazorHelper.cshtml Razor 文件。聲明如下:
@helperTruncat(stringinput,intlength){if(input.Length<=length){@input}else{@input.Substring(0,length)<text>...(Razor)</text>}}在頁面上添加以下代碼:<h2>@RazorHelper.Truncat(@ViewBag.Message,8)</h2>運行,我們看到結果是一樣的。
-----------------------------------------------------------------
2.運用Linq進行帶參查詢如果說,在Index 頁面中添加了參數,那么我們就可以有很多種方式給其傳參,讓其響應事件。 例如,在下面的例子中,可以有一個快捷方式去查看Shanghai 的Restaurant.
第一種:通過@Html.ActionLink()
在RestaurantControl 中添加以下代碼
OdeToFoodDB_db=newOdeToFoodDB();publicActionResultIndex(stringcity){varmodel=fromrin_db.Restaurantswherer.Adress.City==city||(city==null)orderbyr.Nameselectr;returnView(model);}在Restaurant的View 中,Index頁面寫入一下代碼:<p>@Html.ActionLink("To see Restaurant in shanghai","Index","Restaurant",new {city="Shanghai"},null)</p>
第二種:綁定字段
添加DownloadList列表,讓其通過選項進行自由選擇。DownloadList可以綁定字段。在RestaurantControl 中添加以下代碼:
OdeToFoodDB_db=newOdeToFoodDB();publicActionResultIndex(stringcity){ViewBag.City=_db.Restaurants.Select(r=>r.Adress.City).Distinct();varmodel=fromrin_db.Restaurantswherer.Adress.City==city||(city==null)orderbyr.Nameselectr;//varmodel=_db.Restaurants//.Where(r=>r.Adress.City=="Guangdong")//.OrderBy(r=>r.Name);returnView(model);}在Restaurant的View 中,Index頁面寫入一下代碼:@using (Html.BeginForm("Index","Restaurant",FormMethod.Get)){@Html.DropDownList("City",new SelectList(ViewBag.City)) <input type="submit" value="Filter" />}
在這里,我讓DropDownList 綁定了一個dynamic 類型(ViewBag.City)的數據。
新聞熱點
疑難解答