Gary the Llama
Gary the Llama

Reputation: 321

Why isn't my View updating properly?

I'm fairly new to ASP.NET MVC and jQuery. I've got a jQuery UI datepicker that allows the user to select a date. On selection, I have code to send the date parameter into my Index controller action which should then update the View. However, the page isn't updating. Ultimately, I only want to update the table that the data is bound to and not the rest of the page. What's the best way to do this?

Here's my jQuery function:

  $(function () {
  $("#datepicker").datepicker({
     onSelect: function (dateSelected) {
        $.post('<%= Url.Action("Index") %>',
           { date: dateSelected },
           handleSuccess
        );
     }
  });

});

The controller is something like this:

public ActionResult Index(string date)
{
   // ...
   Data = GetData();

   return View(Data);
}

Before I used the OnSelect method, I was just using a button to submit it. It worked just fine then when pressing the button, the data would be returned and the view would update. But when I call it in this new way, I see the proper parameter getting passed in, and the proper data getting returned but the view doesn't change.

Upvotes: 0

Views: 92

Answers (1)

Vadim
Vadim

Reputation: 17957

Your jQuery call submits to the controller action asynchronously. Which means that you are responsible for updating the page. This can be done in your handleSuccess function.

The simplest way to do this I think would be to do this in your success handler. Since your action returns html, you can replace the current content of your table with the new content.

function handleSuccess(data) {
   $('#dataTable').html($(data).find('#dataTable').html())
}

A better solution I would think would be to dynamically return either a ViewResult or a JsonResult depending on some flag passed to the action. Then you can use jQuery Templates to render the result.

Upvotes: 1

Related Questions