ASP.Net MVC 在模型错误中定义页面链接

本文关键字:定义 链接 错误 Net MVC 模型 ASP | 更新日期: 2023-09-27 18:36:27

我在Youtube上关注了一个基本的MVC视频,并看到视频无法解释的错误。我有一个视图列表(如下所示),它给出了以下错误。任何帮助将不胜感激。这可能是一个简单的错误,因为我是 ASP.Net 新手。错误在视图中带星标的页面链接下引发。提前谢谢你。

注意:我假设我必须在我的ProductListViewModel代码中定义PageLinks,但视频没有以这种方式构建它。PagingHelpers是我标记为"HtmlHelpers"的文件夹中的一个类。

错误:"HtmlHelper"不包含"PageLinks"的定义,并且找不到接受类型为"HTMLHelper"的第一个参数的扩展方法"PageLinks"(您是否缺少使用指令或程序集引用?

View:
@model OnlineShoppingStore.WebUI.Models.ProductListViewModel
@{
ViewBag.Title = "Products";
}
@foreach (var p in Model.Products)
{
<div>
    <h3>@p.Name</h3>
    <h4>@p.Price.ToString("c")</h4>
    @p.Description
</div>
}
<div>
   @Html.**PageLinks**(Model.PagingInfo, x => Url.Action("List", new { page = x}))
</div>
ProductListViewModel:
using OnlineShoppingStore.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OnlineShoppingStore.WebUI.Models
{
    public class ProductListViewModel
{
    public IEnumerable <Product> Products{ get; set; }
    public PagingInfo PagingInfo { get; set; }
}
}
PagingHelpers (where I define PageLinks):
using OnlineShoppingStore.WebUI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace OnlineShoppingStore.WebUI.HtmlHelpers
{
    public static class PagingHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html,
                                                 PagingInfo pagingInfo,
                                                 Func<int, string> pageUrl)
        {
            StringBuilder result = new StringBuilder();
            for (int i =1; i <= pagingInfo.TotalPages; i ++)
            {
                TagBuilder tag = new TagBuilder("a");
                tag.MergeAttribute("href", pageUrl(i));
                tag.InnerHtml = i.ToString();
                if (i == pagingInfo.CurrentPage)
                {
                    tag.AddCssClass("selected");
                    tag.AddCssClass("btn-primary");
                }
                tag.AddCssClass("btn btn-default");
                result.Append(tag.ToString());
            }
            return MvcHtmlString.Create(result.ToString());
        }
    }
}

ASP.Net MVC 在模型错误中定义页面链接

您的视图不知道扩展方法PagingLink的位置,因此您需要在视图顶部添加具有正确命名空间using语句:

@using OnlineShoppingStore.WebUI.HtmlHelpers
@model OnlineShoppingStore.WebUI.Models.ProductListViewModel
@{
    ViewBag.Title = "Products";
}
@* the rest of the code *@

下次遇到类似错误时,解决错误的提示可能是您看到的错误消息(尤其是粗体文本):

(是否缺少 using 指令或程序集引用?