[英]How to use Razor efficiently
我正在尝试使用Razor
在View页面中实现此算法,但是,它不显示预期的结果,并且没有任何编译错误。 有什么建议吗? 编辑:我很抱歉,我承认我不是很清楚。 我的问题是我不明白为什么ViewBag.NbrePages
等于0。但是,数据库已被填充。
行动();
[HttpGet]
public ActionResult Rechercher(string rech, string type, int num = 1)
{
int nbLignesDepassees = 10 * (num - 1);
ViewBag.Recherche = Server.HtmlEncode(rech);
ViewBag.Type = Server.HtmlEncode(type);
ViewBag.NumPgeCourrante = num;
if (type == "nomAppMetier")
{
var appsMetiers = _db.AppsMetiers
.Where(x => SqlFunctions.PatIndex("%" + rech + "%", x.nomApplication) > 0)
.OrderBy(x => x.nomApplication)
.Skip(nbLignesDepassees)
.Take(10);
ViewBag.NbrePages = (int)(appsMetiers.Count() / 10) ;
return View("RechercheAppsMetiers",appsMetiers);
}
if (type == "nomPoste")
{
var postes = _db.Postes
.Where(x => SqlFunctions.PatIndex("%" + rech + "%", x.nomPoste) > 0)
.OrderBy(x => x.nomPoste)
.Skip(nbLignesDepassees)
.Take(10);
ViewBag.NbrePages = (int)(postes.Count() / 10);
return View("RecherchePostes", postes);
}
return HttpNotFound();
}
视图();
<ul>
@{
for (int i = 0; i < ViewBag.NbrePages; i++)
{
if(i==1 || i==2 || i==3){
<li class="disabled"><a href="#">&maquo;</a></li>
}else{
<li><a href="#">«</a></li>
}
if (i == ViewBag.NumPgeCourrante)
{
<li class="active"><a href="#">@i <span class="sr-only">(current)</span></a></li>
}
else
{
<li><a href="#">@i </a></li>
}
if(i==ViewBag.NbrePages || i==ViewBag.NbrePages-1 || i==ViewBag.NbrePages-2){
<li class="disabled"><a href="#">»</a></li>
}else{
<li><a href="#">»</a></li>
}
}
}
</ul>
非常感谢 !
与其在视图中拥有太多逻辑,不如考虑以下因素:
一个模型
public class PagesModel
{
public int NumberOfPages { get; set; }
public int CurrentPage { get; set; }
}
类中的辅助方法
public static class Helpers
{
public static bool GetClassNames(int page, int totalPages, int currentPage)
{
var classNames = new List<string>();
var isWithinFirstOrLastThree = page <= 2 || page >= (totalPages - 2);
if (isWithinFirstOrLastThree)
{
classNames.Add("disabled");
}
if (page == currentPage)
{
classNames.Add("active");
}
return string.Join(" ", classNames.ToArray());
}
}
然后,您的观点可能会像
@model PagesModel
@for (int i = 0; i < Model.NumberOfPages; i++)
{
<li class="@Helpers.GetClassNames(i, Model.NumberOfPages, Model.CurrentPage)">
<a href="#">&maquo;</a>
@i
</li>
}
这与您要实现的目标不完全匹配,但是我希望它还是有帮助的。
由于Take(10)
并使用整数除法, NbrePages
将为0或1(如果您有10条以上的记录):
ViewBag.NbrePages = (int)(appsMetiers.Count() / 10) ;
因此,很可能您在appsMetiers
获得的项目少于10个。
基于CSHTM中变量的原始拼写错误的改进建议:
使用好名或强类型模型将有助于避免在原始帖子中使用NbrePges
拼写for
条件:
for (int i = 0; i < ViewBag.NbrePages; i++)
直到运行时访问,才编译CSHTML文件,因此没有编译错误。 由于ViewBag
允许使用任何属性,因此您也不会收到任何智能提示警告。
代替某些ViewBag
考虑使用一些强类型模型或至少将强类型对象用于分页到ViewBag
:
class PagingState
{
public int NumberOfPages { get;set;}
public int CurrentPage { get;set;}
}
并且鉴于:
var pageingState = (PagingState)(ViewBag.Paging);
for(int I = 0; i < pageingState.NumberOfPages; i++)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.