[英]ASP.NET MVC notify of redirect with JavaScript
我有一个简单的动作方法,列出了存储库中的一些数据。 此操作方法的视图使用简单分页。 可以单击URL或输入为server:port/product/2
,其中2是页码。 如果用户输入的页码大于数据页数,我想先将用户重定向到server:port/product/1
,然后通知他们重定向。 重定向部分工作,但我似乎无法找到一种方法来获取传递给action方法的值。
编辑:我在这个问题中错误地使用了QueryString,我真正想要的是传递给action方法的参数。
ProductController的
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通知用户重定向?
也许我错过了一些东西,但似乎你的问题是“如何从没有查询字符串的URL中获取查询字符串值。”
您的重定向URL /Product/List/1
和您提到的上一个URL http://localhost:49997/product/list/2
都没有查询字符串,因此任何尝试访问Request.QueryString
任何内容都将返回空值。
如果您在重定向上的查询字符串中需要某些内容,则需要将其添加到重定向URL:
window.location = '/Product/List/1' + ((pageParam != '') ? '?id=' + pageParam : '');
将操作方法的参数名称从page
更改为id
以与MapRoute
一致。 如果你没有跳过url中动作的名称,那么你不需要第一个MapRoute
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.