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類,具體實現如下
HtmlHelpers
namespace MVCET.Helpers
{
public static class HtmlHelpers
{
public static string Truncat(this HtmlHelper helper, string input, int length)
{
if (input.Length <= length)
{
return input;
}
else
{
return input.Substring(0, length) + "...";
}
}
}
}
這時候,在頁面上只要添加這樣的代碼就可以顯示了:
@using MVCET.Helpers
<h2>@Html.Truncat(@ViewBag.Message as string,8)</h2>
二、 Razor Declarative @Helper Sytnax
1. 在當前頁面添加如下代碼:
@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 檔案。聲明如下:
@helper Truncat(string input, int length)
{
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 = new OdeToFoodDB();
public ActionResult Index(string city)
{
var model = from r in _db.Restaurants
where r.Adress.City == city ||(city==null)
orderby r.Name
select r;
return View(model);
}
在Restaurant的View 中,Index頁面寫入一下代碼:
<p>@Html.ActionLink("To see Restaurant in shanghai","Index","Restaurant",new {city="Shanghai"},null)</p>
第二種:綁定欄位
添加DownloadList列表,讓其通過選項進行自由選擇。DownloadList可以綁定欄位。
在RestaurantControl 中添加以下代碼:
OdeToFoodDB _db = new OdeToFoodDB();
public ActionResult Index(string city)
{
ViewBag.City = _db.Restaurants.Select(r => r.Adress.City).Distinct();
var model = from r in _db.Restaurants
where r.Adress.City == city ||(city==null)
orderby r.Name
select r;
//var model = _db.Restaurants
// .Where(r => r.Adress.City == "Guangdong")
// .OrderBy(r => r.Name);
return View(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)的資料。