dcolumbus
dcolumbus

Reputation: 9722

ASP.NET MVC 2: jQuery call Action, update View?

Controller:

public ActionResult Index()
        {

            // not using the interface right now
            DealsRepository _repo = new DealsRepository();
            var deals = _repo.GetDeals("<Request><ZipCode>92618</ZipCode></Request>");

            return View(deals);
        }

        [HttpPost]
        public ActionResult Index(string data)
        {

            // not using the interface right now
            DealsRepository _repo = new DealsRepository();
            var deals = _repo.GetDeals(data);

            return View(deals);
        }

jQuery:

var url = '<%: Url.Action("Index", "Deal") %>';
var data = '<Request><ZipCode>92618</ZipCode></Request>';

$.post(url, data, function (result) {
    alert(result);
});

What I'm trying to do is refresh (reload) the View with the updated Model... I don't want to use jQuery to update the content. Relaod the View with the updated Model.

In other words, once a user enters some refinements in their search or selects a filter, I need to make the call, and reload the page with the latest Model search results.

Upvotes: 2

Views: 4052

Answers (4)

Tahbaza
Tahbaza

Reputation: 9548

You don't need javascript at all to post a form, which is what it seems you are trying to do.

Just add a submit button to your html form. When the submit button is clicked the form will be posted to the controller and action associated with the html form. That controller and action will return an ActionResult which will be your refreshed view if you so choose...

In your view you can do something like this:

<%Html.BeginForm("ActionName", "ControllerName", FormMethod.Post); %>
<!-- more form fields here -->
<input type="submit" value="Go"/>
<%Html.EndForm(); %>

Upvotes: 2

Basic
Basic

Reputation: 26766

If you're simply going to refresh the page,l there's VERY little advantage to the JS AJAX call unless you're waiting for a timed event in the 1-30 second range

If that's the case, wait until you get a response and simply do a reload in JS:

window.location.reload()

or

history.go(0)

(I recommend the former)

Upvotes: 0

rboarman
rboarman

Reputation: 8214

Sometimes I just reload the page after a submit button click.

<script type="text/javascript">

    $("#SubmitButton").click(function () {
            window.location.reload(true); 
    }); 

</script>

Upvotes: 0

Paul Creasey
Paul Creasey

Reputation: 28824

The view should have a div or similar object with an id (eg myDivId), then in your post, you just need to do

$.post(url, data, function (result) {
     $('#myDivId').html(result);
});

Upvotes: 0

Related Questions