简体   繁体   中英

Cancel / end the rendering of a partial view using MVC controller

I'm trying to speed up the return of search results in my MVC web app. If the user searches for one phrase and then searches for another straight afterwards I'd like to cancel the original search, or realistically, cancel the rendering of results as this is what is taking time.

Edit: the search box searches in real-time, hence if you type in something with lots of results, like "the", and then quickly change it to something more specific, then the original search holds up the latest one.

I originally thought that it was the database interaction that was the bottleneck (hence my question about cancelling db search requests here ), but it's the rendering of all the results in a partial view that's the overhead:

My SearchContoller has this form:

public ActionResult Search(string query, string time) {

    // Go off and do search, returning results

    return PartialView("SearchResults", results);
}

If the Search controller method is used again while the first PartialView is rendering, can I cancel the original one somehow? For example in the view can I check a flag and cancel if that flag is set elsewhere?

View:

@model SearchResultModel

@if (Model.ResultType1.Count > 0) {
  <h2>Results 1</h2>
    <dl>
      <dt>Results:</dt>
        @foreach (var result in Model.Results1) {
           if (FlagInControllerToStopThis) break; // OR SOMETHING SIMILAR??
        <dd> <!--Each result is returned here--></dd>
      }
    </dl>
}

Why not have the search box rendered as invisible, and then include some jQuery code in documentReady() to show the text box? If there are no results, it will then be immediate, but if there are many, when the page is returned it can't be used.

Theoretically the user could use another screen to do another query, but I think that may be beyond the scope of the question.

Edit given comment below

If you're using MVC 4, you could make the search method asynchronous , see this article on how to do that. One could then potentially cancel that using something like a ManualResetEvent , provided the code that was searching could see if it was set and stop itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM