Question

I'm pretty new to MVC so this may seem like an obvious question, but when posting to my ActionResult, the ActionResult gets called, but the View doesn't change.

What I'm doing is having a basic search page where a user can search my database and the results are returned and paginated.

Here is javascript that calls that ActionResult in my controller.

    function SubmitSearch() {

    var searchBox = document.getElementById('searchBox');

    $.post("MyController/SearchResults/",
    {
        searchString: searchBox.value,
        page: 0
    });

    window.location = "../DriverStudio/Drivers/SearchResults/" + searchBox.value + '/0';
}

My current solution (which is a horrible hack) is to comment out the $.post(since my route is set up in a way where the window.location will call the SearchResutls ActionResult) and set the window.location to what the user searched for, starting at page 0.

There has to be a better way. What should I do?

Was it helpful?

Solution

Set up your SearchResults action to return a partial view containing only the part of the page to be updated when the search is performed. This piece should be contained in some container, making it easy to replace. Then use the callback mechanism on the post method to replace the contents of that DIV with the partial view result returned from your SearchResults action. Return false from your handler to stop the default submit action from being taken.

function SubmitSearch() { 

    var searchBox = $('#searchBox'); 

    $.post("MyController/SearchResults/", 
    { 
        searchString: searchBox.val(), 
        page: 0 
    }, function(data) {
        $('#searchResults').html( data );
    }); 

    return false;
}

This assumes some view code that looks something like:

 <% using (Html.BeginForm()) { %
      <label for="searchBox">Search:</label>
      <%= Html.TextBox("searchBox") %>
 <% } %>
 <div id="searchResults">
 </div>

OTHER TIPS

I'm not to familiar with MVC, but what does your ActionResult do other than redirect the user to that URL you have in window.location?

You probably need to implement a callback, from jQuery docs:

 jQuery.post( url, data, callback, type )

So you're passing the URL and the data, but nothing about what you want to do with the returned data.

 $.post( "MyController/SearchResults/", 
         {searchString: searchBox.value,page: 0},
         function(result){
                //do something with what your actionresult returns here
                window.location = result.url;
         }
       );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top