私は解決策を見つけました。これには、Session(またはCacheまたはTempData)での検索を維持することが含まれ、それ以上のものはありません。このソリューションは、実際の状況に適応でき、特定のクラスJQueryを必要としないため優れています。
魔法のトリックは、インデックスActionResult(またはデフォルトのActionResultで、グリッドページをデフォルトの動作でレンダリングします)内で発生します。
コード例:
[HttpGet]
public ActionResult Index()//My default action result that will render the grid at its default situation
{
SearchViewModel model = new SearchViewModel();
if (Request.IsAjaxRequest()) //First trick is here, this verification will tell you that someone sorted or paged the grid.
{
if (Session["SearchViewModel"] != null) //If session is not empty, you will get the last filtred values from it.
model = (SearchViewModel)Session["Filtro"];
}
else // If it is not an AjaxRequest, you have to clear your Session, so new requests to Index with default behavior won't display filtred values.
{
Session["SearchViewModel"] = null;
}
model.GridResult = ExecuteFilter(model); // OPITIONAL! This code dependes on how is your real world situation. Just remember that you need to return a default behavior grid if the request was not called by the WebGrid, or return filtred results if WebGrid requested.
return View(model);
}
したがって、これがデフォルトのActionResultになります。リクエストがWebGridのページングまたは並べ替えイベントによって呼び出されたかどうかを確認し、フィルタリングされた結果を返すか、通常の動作の結果を返すかを決定します。
次のステップは、POSTActionResultの検索です。
[HttpPost]
public ActionResult Index(SearchViewModel pesquisa) // IMPORTANT!! It is necessary to be the SAME NAME of your GET ActionResult. The reason for that I know, but won't discuss here because it goes out of the question.
{
SearchViewModel model = new SearchViewModel();
model.GridResult = ExecuteFilter(pesquisa); // Execute your filter
Session["SearchViewModel"] = model; //Save your filter parameters on Session.
return View("Index", model);
}
それでおしまい。Index.cshtmlにはトリックがありません。SearchFormをActionResultインデックスに追加し、SearchViewModelをパラメーターとして渡します。
なぜこのソリューションが機能するのですか?
クリックして並べ替えまたはページングすると、WebGridは次のようなJavaScriptを実行します。
$('#yourGrid')。load('現在のページを表示するために使用されるURLと、いくつかのページングまたは並べ替えパラメーターを渡しますが、これらはWebGridによって使用されます').load()メソッドを実行するため、リクエストGETになり、インデックスGETActionResultにヒットします。ただし、これはAJAX呼び出しであるため、私たちの魔法のトリックは、Sessionに保存したパラメーターを使用してフィルターを再度実行します。
私が警告するユニークな詳細は、デフォルトのグリッド動作に関するものです。GET Index ActionResultは、Sessionにフィルターがあるかどうかに関係なく、有効なグリッド結果を返す必要があります。