How to refresh my Partial View after Ajax Post in MVC?

12,376

Solution 1

Do I need to create a post method for _WorkingTimeData?

Yes, you need to create. But, Get would be fine too.

Do I need to create a ViewModel for the Partial View? Not needed. If required you can create.

But, by looking at your partial view you are just using ViewData[""]. So, you need not to create any ViewModel.

Just create a method in Controller returning _WorkingTimeData PartialView. And call that method by JQuery ajax on your DatePicker change event and replace the contents of the Div.

For example. Controller

public PartialViewResult WorkingTimeData()
{
    ViewData["WorkedTimeToday"]="NEW VALUE";
    ViewData["HoursPerDayContract"] = "NEW VALUE";
    return this.PartialView("_WorkingTimeData");
}

JavaScript

       $("DATEPICKERELEMENT").change(function() {
           $.ajax({
               url: "/CONTROLLER/WorkingTimeData",
               type: "get"
           }).done(function(data) {
               alert(data);
               $("#divisionIdContainingPartialView").html(data);
           }).fail(function() {
               alert('error');
           });
       });

Solution 2

I wrote a post that details why you need to break the logic of thinking about partial views client-side. If you're interested you can find it here.

The TL;DR version is simply, all you have client-side is HTML. There's no knowledge about what was or was not rendered to the response via a partial view. As a result, the real question is "How do I change a portion of my HTML page based on an AJAX response?". In the simplest form, you simply select some element on the page and then alter its inner HTML. You can do that with some custom HTML created client-side or you can actually pass back an HTML document as your AJAX response and then insert that.

Share:
12,376
Cajux94
Author by

Cajux94

Updated on August 02, 2022

Comments

  • Cajux94
    Cajux94 over 1 year

    So basically I'm trying to show some Profile Data in my MVC Application. Right now, everytime I click on a date on my Telerik Kendo Calendar, I can refresh the whole page and update the data I want.

    However, instead of refreshing the whole I just want to refresh the partial views that shows only the data that updates after selecting the date.

    Index.cshtml

    <!--CODE-->
      @Html.Partial("_WorkingTimeData")
    <!--CODE-->
    

    _WorkingTimeData.cshtml

     var workedTime = ViewData["WorkedTimeToday"];
     var hoursPerDay = ViewData["HoursPerDayContract"];
    
        <p>You worked @workedTime hours</p>
        <p>Hours Per Day (Contract) @hoursPerDay Hours</p>
    

    Yes, right now I'm ViewDatas and it works.

    This is the ajax code in Index.cshtml

      $.ajax({ url: '/Profile/Index',
                                dataType: "json", 
                                type: "POST", 
                                data: JSON.stringify(10), 
                                success: function(returl){ 
                                    alert('It worked'); 
                                    location.href=returl.Url;
                                }, 
                                error: function(jqXHR,responseText,textStatus){ alert(jqXHR.responseText) } });
    

    Controller

        [HttpPost]
        public ActionResult Index(string number){
    
            //THINGS TO DO
            var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile");
            return Json(new { Url = redirectUrl });
        }
    

    Well I'm very new to this, and I've been doing my research. However I still have some questions: - Do I need to create a post method for _WorkingTimeData instead of Index like I have? - Do I need to create a ViewModel for the Partial View?

    Thanks

    EDIT NUMBER 2 FOR VISHAL:

    This didn't work at all, not even an alert, because, strangely, it doesn't recognise the calendar...

    $("#calendar").kendoCalendar({
                            change : function() {
                                $.ajax({
                                    url: "/Profile/WorkingTimeData",
                                    type: "get"
                                }).done(function(data) {
                                    $("#profile-timeline").html(data);
                                });
                            }});
    

    It says $("#calendar").kendoCalendar is not a function (Telerik says that it's this way)

    As for this, it reached the controller but didn't update anything:

     function change() {
                            alert("Escolheste outro dia");
                            var calendar = $("#calendar").data("kendoCalendar");
                            var current = calendar.current();
                            alert(current);
                                        $.ajax({
                                            url: "/Profile/WorkingTimeData",
                                            type: "get"
                                        }).done(function(data) {
                                            $("#profile-timeline").html(data);
                                        });
                                    }
    

    I think it's because of the profile-timeline... It's a div in my view