·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> ASP.NET MVC中几个运用技巧

ASP.NET MVC中几个运用技巧

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

asp.net MVC中几个运用技巧

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)的数据。