Darcy
Darcy

Reputation: 5368

how to call controller from button click without using ajax mvc

I'm new to web programming in general so this is probably a really simple question. I couldn't find anything on the web however.

What I want to do is call my controller with the typed search string and return the results from a database and paginate the results. Right now I am using a function that is called when the button is pressed. The function looks like so:

function SubmitSearch() {

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

    $.post("MyController/MyAction/",
    {
        searchString: searchBox.value,
        page: null
    }, function(result) {
        $('#searchResults').html(result);
        searchButton.value = "Search";
    });
}

What happens is my controller is called, and my searchResults div is populated with the results and paginated. The user can click any search result returned to view the details.

The problem is when the user clicks the browsers 'back' button, the page returns to the state before the search was entered, and this is because of the ajax call. What I want to do is, call the controller and have the page load like google would. Instead of using a PartialView, I would use a View (my guess).

How would I call the controller and have the page RELOAD with the results. I must be missing something fundamental because this definitely seems like it should be easy.

Upvotes: 0

Views: 11564

Answers (3)

David Glenn
David Glenn

Reputation: 24522

If you don't want to use AJAX then you need to place your text field in a form element on your page, something like:

<form action="MyController/MyAction/" method="get">
  <input id="SearchBox" name="SearchBox" type="text" />
  <button type="submit">Search</button>
</form>

Then in your controller return the view with the list of results.

You probably also want to look into RESTful URLs and the PRG (Post, Redirect, Get) pattern to maintain the integrity of the back button and enable correct bookmarking of pages etc.

Upvotes: 2

cem
cem

Reputation: 1911

Aspx:

<% using (Html.BeginForm<MyController>(m => m.MyAction(null)) { %> 
    <%= Html.TextBox("q"); %>
<% } %>
// Listing

Controller:

public class MyController : Controller
{
    public ActionResult MyAction(string q)
    {
        var repository; // instance of your repository.

        if (String.IsNullOrEmpty(q))
        {
            return View(repository.GetAllBlogs());
        }
        return View(repository.SearchBlogs(q));
    }
}

Upvotes: 1

Lazarus
Lazarus

Reputation: 43074

I think you might actually be looking for an AJAX History library to help when the Back button is pressed rather than altering your app. Take a look at this blog post.

Upvotes: 1

Related Questions