【发布时间】:2014-02-05 18:22:20
【问题描述】:
我有一个简单的操作方法,它列出了存储库中的一些数据。此操作方法的视图使用简单的分页。可以单击 URL,也可以将其输入为 server:port/product/2,其中 2 是页码。如果用户输入的页码大于数据页数,我想首先将用户重定向到 server:port/product/1 并通知他们他们已被重定向。重定向部分有效,但我似乎找不到将值传递给操作方法的方法。
编辑:我在这个问题中错误地使用了 QueryString,我真正想要的是传递给操作方法的参数。
产品控制器
public ActionResult List(int page =1)
{
ProductsListViewModel model = new ProductsListViewModel();
model.Products = _repository.Products.OrderBy(x => x.ProductId)
.Skip((page -1) * 4)
.Take(4);
model.PagingInfo = new PagingInfo()
{
CurrentPage = page,
ItemsPerPage = 4,
TotalItems = _repository.Products.Count()
};
//this correctly redirects
if (page > model.PagingInfo.TotalPages)
{
return RedirectToAction("List", new { page = 1 });
}
return View(model);
}
JavaScript
var pageParam = "@Request.QueryString["id"]"
var pageTotal = "@Model.PagingInfo.TotalPages";
var pageCurrent ="@Model.PagingInfo.CurrentPage";
console.log('this is the current page: ' + pageCurrent);
console.log(pageTotal);
console.log(pageParam);
function notifyRedirect(pageTotal, pageParam) {
if (pageParam > pageTotal) {
alert('you entered ' + pageParam + ', an invalid page parameter and were redirected');
window.location = '/Product/List/1';
}
}
notifyRedirect(pageTotal,pageParam);
路线
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
当页面加载时,pageTotal 和 pageCurrent 变量被打印到控制台,但我在尝试获取 QueryString 值时得到一个空字符串。想着可能是参数名不对,决定使用QueryString的积分索引,结果报错:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
为什么http://localhost:49997/product/list/2,完全限定的 URL 仍然给我一个空的 QueryString 值?如何使用 JS 通知用户重定向?
【问题讨论】:
-
QueryString是“?”之后的 url 的一部分并由“&”分隔的“name=value”对组成 - 你没有它 -
@wootscootinboogie,您要先通知然后重定向吗?还是先重定向然后通知?您的 javascript 似乎在做 - 通知和重定向,但在您的问题中,我看到您发出警报然后重定向。
-
@ramiramilu 我想重定向然后通知。我不知道我错过了什么,但即使使用 Request["id"] 也不会给我任何回报。但是,如果我使用 Request.Url,我可以将参数视为 URL 的一部分,但对于任何 JS 使用,我似乎都无法掌握它。
-
使用 MVC 路由,Request 不携带
id作为单独的项(不在 QueryString 中,不在 Form 中等)。id是网址的一部分。它是 MVC 框架,它根据路由从 url 中提取id的值,如果参数名称与路由中的名称匹配,则将其作为操作参数传递。 -
@Igor 很高兴知道。检查更新的路线部分,我删除了除一条路线之外的所有路线,但是当我尝试使用 @Request["id"] 打印参数我的列表视图时,我得到一个空白字符串。为什么会发生这种情况?
标签: c# javascript asp.net-mvc