【问题标题】:Ajax Sorting and Filtering Is Not Working in MVCAjax 排序和过滤在 MVC 中不起作用
【发布时间】:2015-03-27 00:59:45
【问题描述】:

在每个包含列表的索引视图页面上,我使用 ASP.NET MVC AJAX 对列表进行排序和过滤。该列表位于部分视图中。一切看起来都很好,直到我看到带有参数的视图(参考键/FK)

我没有添加任何路由,只是使用默认路由:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

所以网址是http://localhost:49458/TimeKeeper/New?billingID=7。如果该格式的 url,AJAX 排序和过滤器不起作用。我尝试添加一条新路线:

routes.MapRoute(
    name: "TimeKeeperNew",
    url: "TimeKeeper/New/{billingID}",
    defaults: new { controller = "TimeKeeper", action = "New", billingID = "" }
);

所以网址变成:http://localhost:49458/TimeKeeper/New/7。 现在,ajax 排序和过滤器正在工作。

有没有人可以解释一下,有什么问题吗?我使用了正确的方式(通过添加新路线)还是有其他方式?

【问题讨论】:

  • 字面意义上的"billingID" != "id"
  • @ErikPhilips 我明白了,通常{id} 是主键,对吧?但billingID 是Timekeeper 表的外键。我需要通过billingID 显示数据。你能更深入地解释一下吗?还有其他方法还是正确的方法?
  • 为什么不直接将参数传递为id - 你仍然可以过滤数据 - db.TimeKeepers.Where(x => x.BillingID == ID)
  • @StephenMuecke,谢谢,它也适用于{id}。所以{id} 不仅适用于PK,也适用于FK 或任何其他领域,对吧?如果有 2 个参数,比如billingIDclientGroupID,那会怎样?我不太了解路由,您能帮我在答案中解释一下吗?

标签: ajax asp.net-mvc asp.net-mvc-routing asp.net-mvc-5.1


【解决方案1】:

我什至不明白你为什么说主键,因为 MVC 没有这个概念。

只有(假设在这个答案的持续时间内直到休息):

routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Home", 
                  action = "Index", 
                  id = UrlParameter.Optional }
);

任何未定义id 的路由都将附加到带有值的url。

Url.Action("New", "TimeKeeper", new { billingID = 7 })

总会产生

http://localhost:49458/TimeKeeper/New?billingID=7

因为"billingID" != "id"

所以你的选择是另一个我不推荐的MapRoute,或者使用Id

Url.Action("New", "TimeKeeper", new { id = 7 })

总是产生:

http://localhost:49458/TimeKeeper/New/7

可选:

public class TimerKeeperController
{
  public ActionResult New(string id)
  {
    int billingId;
    if (!string.TryParse(id, out billingId)
    {
      return RedirectToAction("BadBillingId")
    }
    ....
  }
}

休息

如果有 2 个参数,比如 billingID 和 clientGroupID,会怎样?我不太了解路由,您能帮我在答案中解释一下吗?

现在你需要另一个 MapRoute:

routes.MapRoute(
  name: "Default2",
  url: "{controller}/{action}/{id}/{id2}",
  defaults: new { controller = "Home", 
                  action = "Index", 
                  id = UrlParameter.Optional,
                  {id2} = UrlParameter.Optional }
);

并且它必须在前一个 MapRoute 之前或之后,因为任何适用于这条路线的东西都适用于前一条路线,因此永远不会调用这条路线。我现在记不清具体是哪条路了,但如果你测试一下,你会很快弄清楚的。

那么你可以:

 http://localhost:49458/TimeKeeper/Copy/7/8

与:

  public ActionResult Copy(string id, string id2)
  {
    ....
  }

笔记

是的,您不必使用字符串并解析值,您可以在 MapRoute 上使用约束,或者仅使用 Int 并在有人手动键入 http://localhost:49458/TimeKeeper/New/Bacon 时抛出错误。

【讨论】:

  • 我认为 {id} 是主键,但它不是。谢谢你的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
相关资源
最近更新 更多