问题描述
我正在使用.NET Core MVC。我尝试创建的导航链接似乎无法正常工作。我有以下模型:
public class Model
{
public long ModelID { get; set; }
public string Name { get; set; }
public string SolverType { get; set; }
public string ProgramType { get; set; }
}
传递的此viewmodel是:
public class ModelsListviewmodel
{
public IEnumerable<Model> Models { get; set; }
public PagingInfo PagingInfo { get; set; }
public string CurrentProgramType { get; set; }
}
视图为:
@model IEnumerable<string>
<a class="btn btn-block btn-outline-secondary"asp-action="Index"
asp-controller="Home" asp-route-type="">
Home
</a>
//THESE DON'T LINK APPROPRIATELY TO THE CONTROLLER
@foreach (string type in Model)
{
<a class="btn btn-block btn-outline-secondary"
asp-action="Index" asp-controller="Home"
asp-route-type="@type"
asp-route-modelPage="1">
@type
</a>
}
Home控制器的操作是:
public ViewResult Index(string type,int modelPage = 1)
=> View(new ModelsListviewmodel
{
Models = repository.Models
.Where(m => type == null || m.ProgramType == type)
.OrderBy(m => m.ModelID)
.Skip((modelPage - 1) * PageSize)
.Take(PageSize),PagingInfo = new PagingInfo
{
CurrentPage = modelPage,ItemsPerPage = PageSize,TotalItems = type == null ?
repository.Models.Count() :
repository.Models.Where(e =>
e.ProgramType == type).Count()
},CurrentProgramType = type
});
页面呈现后,将显示视图组件按钮,但将鼠标悬停在链接上时将不起作用或显示链接。他们似乎没有在控制器内调用任何动作。
编辑:这是在我的Startup.cs
文件中定义的路由:
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute("typepage","{type}/Page{modelPage:int}",new { Controller = "Home",action = "Index" });
endpoints.MapControllerRoute("page","Page{modelPage:int}",action = "Index",modelPage = 1 });
endpoints.MapControllerRoute("type","{type}",modelPage = 1 });
endpoints.MapControllerRoute("pagination","Models/Page{modelPage}",modelPage = 1 });
endpoints.MapDefaultControllerRoute();
});
EDIT2:这是呈现按钮的ViewComponent:
public IViewComponentResult Invoke()
{
return View(repository.Models
.Select(x => x.ProgramType)
.distinct()
.OrderBy(x => x)); ;
}
EDIT3:
这是PageingInfo
类,用于处理剩余的评论:
public class PagingInfo
{
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPages => (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage);
}
解决方法
问题似乎出在您生成链接的URL的方式上。生成的URL类似于/home/index/my-type/1
,其中my-type
是模型的假定值。
由于您在服务器中的映射期望页面以单词Page
为前缀,因此您永远不会找到匹配的路由。您需要将创建链接的代码更改为以下内容:
<!--
Check modelPage value is now "Page1". Here is the change which generates the URL like
"/home/index/my-type/Page1" as you mapped server side.
-->
<a class="btn btn-block btn-outline-secondary"
asp-action="Index" asp-controller="Home"
asp-route-type="@type"
asp-route-modelPage="Page1">
@type
</a>
此外,请确保导入标签帮助程序
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers