【问题标题】:How can I use HTML Anchors in MVC 4?如何在 MVC 4 中使用 HTML 锚点?
【发布时间】:2012-09-29 00:39:54
【问题描述】:

我有一个显示用户 cmets 的网页。我默认页面显示最近的 10 个。在底部,当用户点击“显示更多”时,下方会出现另外 10 个 cmets。用户可以多次单击该按钮,每次底部会多显示 10 个 cmets。问题是用户必须再次向下滚动。我想使用锚点来选择显示的最后一条评论。

在我看来,我有:

@{ int i = 1; }
@foreach (var item in Model) {
    <div class="Comment" id="Comment-@i">
        @Html.DisplayFor(modelItem => item.CommentText)
    </div>

    i++;
}

@{int numCommentsToDisplay = 10;}
@if (Session["numCommentsToDisplay"] != null) {
    numCommentsToDisplay = Convert.ToInt32(Session["numCommentsToDisplay"]); 
}

@Html.ActionLink("Show More", "Index", new { numCommentsToDisplay = numCommentsToDisplay + 10 })

我的控制器包含:

 public ActionResult Index(int numCommentsToDisplay = 10) {
     this.HttpContext.Session.Add("numCommentsToDisplay", numCommentsToDisplay.ToString());
     var latestComments = db.Comments.Take(numCommentsToDisplay).OrderByDescending(c => c.TimeStamp).ToList();

     return View(latestComments);
 }

当用户第一次点击“显示更多”时,会显示20个cmets,如何选择第11条评论?我已经设置了 ID 并手动导航到 http://localhost:49208/Comment?numCommentsToDisplay=20#Comment-11 就可以了

谢谢

【问题讨论】:

    标签: c# asp.net-mvc razor asp.net-mvc-4


    【解决方案1】:

    我已经解决了我自己的问题哇!

    我发现 Html.ActionLink() 的重载可以完成这项工作:

    public static MvcHtmlString ActionLink(
        this HtmlHelper htmlHelper,
        string linkText,
        string actionName,
        string controllerName,
        string protocol,
        string hostName,
        string fragment,
        Object routeValues,
        Object htmlAttributes
    )
    

    所以我将我的锚作为片段传递:

    @Html.ActionLink("Show More", 
                     "Index", 
                     "Comment",
                     null,
                     null, 
                     String.Format("Comment-{0}", numCommentsToDisplay + 1),
                     new { numCommentsToDisplay = numCommentsToDisplay + 10},
                     null
                     )
    

    我在这里找到了答案:Including an anchor tag in an ASP.NET MVC Html.ActionLink

    感谢大家的意见

    【讨论】:

      【解决方案2】:

      我建议使用一些脚本客户端大小。

      您使用的是 MVC4,我的建议是利用 WebApi。 设置一个 api 控制器以返回分页的 cmets 并使用 Knockout.js 将结果呈现到页面中。

      【讨论】:

      • 我以前没有尝试过的东西,我现在已经解决了我的问题,但是当我有时间的时候会看看你的建议。谢谢
      • 这可能是一个不错的附加功能,但如果页面也可以在没有 JavaScript 的情况下运行,那几乎总是好的。
      【解决方案3】:
      @Html.ActionLink(
              "Show More",                        
              "Index",                    
              new { numCommentsToDisplay = numCommentsToDisplay + 10 },          
              new { name = string.Format("Comment-{0}",numCommentsToDisplay) }      
          )
      

      【讨论】:

      • 我无法得到您的答复。那是传入 HtmlAttributes 吗?哪个不会通过我的锚?还是我错过了什么?
      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多