I've got a simple action method that lists some data from a repository. The view for this action method uses simple paging. The URL can be clicked on, or entered as server:port/product/2 where 2 is the page number. If the user enters in a page number that's greater than the number of pages of data, I want to redirect the user to server:port/product/1 first and the notify them they were redirected. The redirecting part works, but I can't seem to find a way to get the value passed to the action method.
EDIT: I used QueryString incorrectly in this question, what I really want is the parameter passed to the action method.
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
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
When the page loads, the pageTotal and pageCurrent variables are printed to the console, but I get an empty string when trying to get the QueryString value. Thinking that maybe I had the name of the parameter wrong, I decided to use the integral index of the QueryString and was presented with the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How is it that http://localhost:49997/product/list/2, the fully qualified URL still gives me an empty QueryString value? How can I use JS to notify the user of the redirect?
QueryStringis part of a url that comes after "?" and consists of "&"-separated "name=value" pairs - you don't have itidas a separate item (not in QueryString, not in Form, etc).idis part of url. It is MVC framework that extractsid's value from url based on routing and passes it as action parameter if parameter name matches that in the route.