您的位置:首页 > 编程语言 > ASP

ASP.NET MVC中几个运用技巧

2015-12-19 17:54 573 查看
1. Razor Helpers 的运用:

例如,定义好 ViewBag.Message = "Welcome to asp.net MVC!";我要在界面上显示

"Welcome ..."; 那我们一般有2种操作,3种实现操作:

2种操作:http://www.kmnk03.com/hxpfk/npx/342.html

Extension Method off HtmlHelpers 和 Razor Declarative @Helper Sytnax

3种实现方式:

一、 Extension Method

在当前项目下建立一个文件夹,命名为Helpers,在这个文件夹下添加 HtmlHelpers类,具体实现如下 http://www.kmnk03.com/hxpfk/dzpz/334.html namespace MVCET.Helpers
{
public static class HtmlHelpers
{
public static string Truncat(this HtmlHelper helper, string input, int length)
{
if (input.Length <= length)
{
return input;
}
elsehttp://www.kmnk03.com/hxpfk/tf/335.html
{
return input.Substring(0, length) + "...";
}
}
}


这时候,在页面上只要添加这样的代码就可以显示了:

@using MVCET.Helpershttp://www.kmnk03.com/hxpfk/npx/343.html


@Html.Truncat(@ViewBag.Message as string,8)

二、 Razor Declarative @Helper Sytnax

1. 在当前页面添加如下代码:

@helper Truncat(string input, int length)

{http://www.kmnk03.com/hxpfk/py/336.html

if(input.Length<=length)

{

@input

}

else

{

@input.Substring(0,length)...(Razor)

}

}

再添加这行代码:


@Truncat(@ViewBag.Message as string, 8)

显示的结果和上面的事一模一样的。

2. 添加App_Code 文件夹,然后添加RazorHelper.cshtml Razor 文件。声明如下:

@helper Truncat(string input, int length)
{
if(input.Length<=length)
{
@input
}
else
{http://www.kmnk03.com/hxpfk/npx/337.html
@input.Substring(0,length)...(Razor)
}


在页面上添加以下代码:


@RazorHelper.Truncat(@ViewBag.Message,8)

运行,我们看到结果是一样的。

-----------------------------------------------------------------

2.运用Linq进行带参查询

如果说,在Index 页面中添加了参数,那么我们就可以有很多种方式给其传参,让其响应事件。 例如,在下面的例子中,可以有一个快捷方式去查看Shanghai 的Restaurant.

第一种:通过@Html.ActionLink()

在RestaurantControl 中添加以下代码

OdeToFoodDB _db = new OdeToFoodDB();
public ActionResult Index(string city)
{http://www.kmnk03.com/hxpfk/npx/338.html
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页面写入一下代码:

@Html.ActionLink("To see Restaurant in shanghai","Index","Restaurant",new {city="Shanghai"},null)

第二种:绑定字段

添加DownloadList列表,让其通过选项进行自由选择。DownloadList可以绑定字段。

在RestaurantControl 中添加以下代码:

OdeToFoodDB _db = new OdeToFoodDB();
public ActionResult Index(string city)
{http://www.kmnk03.com/hxpfk/py/339.html
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;http://www.kmnk03.com/hxpfk/npx/340.html
//var model = _db.Restaurants
// .Where(r => r.Adress.City == "Guangdong")
// .OrderBy(r => r.Name);
return View(model);
} http://www.kmnk03.com/hxpfk/npx/341.html

在Restaurant的View 中,Index页面写入一下代码:

@using (Html.BeginForm("Index","Restaurant",FormMethod.Get))

{

@Html.DropDownList("City",new SelectList(ViewBag.City))
kmnk03.com

}www.kmnk03.com

在这里,我让DropDownList 绑定了一个dynamic 类型(ViewBag.City)的数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: