Asp.net mvc form post and paging
I have an action method Search, which is called when a form is posted. There could be thousands of search resulst based on posted values of form. I want to sh开发者_如何学运维ow Search View page by page, but how can I know what form values was posted first time? so that I can call Search View by passing page parameters.
The best approach would be to embrace the statelessness of the system. Each time you render the view, include in the page the values you'd need on the next action request. They could be added to the query string on the action link, added as form elements and the link invokes a POST (the latter sounds best, since the search term is likely a form input element in and of itself).
Simply pre-populate the search term text input (I'm assuming that's what you're using) with the provided search value each time you render the view. The page number can be appended to the query string on the paging links. Etc.
That way each subsequent request is fully-realized and independent of any previous requests. The search term, the page number, perhaps the page size, etc. should all be passed to the action each time.
In my app all the action methods that provide data to grids take as a parameter an instance of this class:
public class QuerySettings
{
private int page;
public QuerySettings()
: this(true)
{
}
public QuerySettings(bool pagingEnabled)
{
this.Page = 1;
this.Rows = 10;
this.PagingEnabled = pagingEnabled;
}
public int Rows { get; set; }
public string SortColumn { get; set; }
public string SortOrder { get; set; }
public string Search { get; set; }
public bool PagingEnabled { get; set; }
public int Page
{
get { return page; }
set { page = Math.Max(1, value); }
}
}
This object is passed to service methods in by Business Layer which can use the information passed to apply appropriate sorting / filtering. They then return the data wrapped in:
public class QueryResult<T>
{
public QueryResult()
{
}
public QueryResult(QuerySettings settings, IList<T> items, int currentPage, int totalPages, int totalItems)
{
Settings = settings;
Items = items;
CurrentPage = currentPage;
TotalPages = totalPages;
TotalItems = totalItems;
}
public QuerySettings Settings { get; private set; }
public int CurrentPage { get; private set; }
public int TotalPages { get; private set; }
public int TotalItems { get; private set; }
public IList<T> Items { get; private set; }
public IEnumerable<T> AsEnumerable()
{
return this.Items;
}
}
精彩评论