1

This is my first MVC project and I've been trying to figure out how to refresh a Partial View after calling a controller method from AJAX.

My classes look like this and I want to add as many courses as I want for a semester in one view.

    public class CourseViewModel
    {
        public int SemesterID {get; set;}
        public List<Course> Courses {get; set;}  
    }
    public class Course
    {
        public string CourseID {get; set;}
        public string CourseTitle {get; set;}
    }

An Example page looks like this:

enter image description here

In my view, I set up a typeahead for the Course textbox. When a user select a course from a list of typeahead suggestion, I call the SaveCourse method in the controller and it successfully saves. The problem is that I cannot refresh the Partial View after the save occurs.

My View (Index.cshtml):

@using Project.ViewModels;
@model Project.ViiewModels.CourseViewModel


<div id="divCourseTypeahead">
    <input class="typeahead form-control" type="text" />
</div>

<div id="listCourses">
    @{Html.RenderPartial("_CourseList");}
</div>


<script type="text/javascript">
    $(document).ready(function () {
        $('#divCourseTypeahead .typeahead').typeahead({
            //setup typeahead
        }).on('typeahead:select', function(obj, datum){
        var semesterId = @Model.SemesterID
        $.ajax({
            type: "GET",
            url: "/Course/SaveCourse/",
            data: { semesterId: semesterId, courseId: datum.id },
            success: function (result) {
                alert(result);
            }
        });
    });

 </script>

What I've tried (1):

I tried return a PartialVeew from SaveCourse.

public PartialViewResult SaveCourse(int semesterId, string courseId)
{
    //Insert course
    
    CourseViewModel data = new CourseViewModel(semesterId);
    return PartialView("_CourseList", data);
}

When I do this, the PartialView does not get refreshed and the alert(result); in ajax success function does not get called.

What I've tried (2):

public ActionResult SaveCourse(int semesterId, string courseId)
{
    //Insert course
    
    return RedirectToAction("Index", "Course", new {id=semesterId});
    //in Index, I return `CourseViewModel`

}

When I do this, the alert(result); in AJAX success function gets called so I added $('#listCourses').html(result); in the success function then the PartialView does refresh but I get two textboxes like the image below.

enter image description here

I've tried many other options but I am so confused. Could someone please help me how I can achieve what I want to do?

Community
  • 1
  • 1
kabichan
  • 1,063
  • 4
  • 19
  • 49
  • You have not even shown you ajax method. How can we possibly understand what is wring with your code. –  Mar 18 '16 at 22:53
  • @StephenMuecke I stated that the Saving function is working fine so I wasn't worried about the Ajax part and didn't want to make my question too long. I edited my question to add the simpler version so could you undo the downvote? – kabichan Mar 18 '16 at 22:58
  • 2
    **What I've tried(1)** + `$('#listCourses').html(result);` See here http://stackoverflow.com/questions/19392212/how-to-use-jquery-or-ajax-to-update-razor-partial-view-in-c-asp-net-for-a-mvc-p – Jasen Mar 18 '16 at 23:05
  • 1
    I assume the real ajax code is actually appending the partial view your returning to the DOM - e.g. `$(someElement).append(result);` - you need to show the real code. That suggests that your `__CourseList.cshtml` partial in option 1 actually includes the input so your repeating it. And option 2 will not work. Ajax calls do not redirect so calling `RedirectToAction()` will only return the complete `Index.cshtml` view and append it to the DOM (which will duplicate the input. –  Mar 18 '16 at 23:16
  • 1
    And if option 1 is not appending the partial to the DOM (and you `alert()` is not displayed), then your controller method is probably throwing an exception. Use you browser tools to debug your code. What errors are you getting in the console? –  Mar 18 '16 at 23:19
  • @StephenMuecke When I change option1 to `$(someElement).append(result)` the `alert()` gets called but it appends the whole page...like repeats the textbox and partial view. I'll update my question to show the result. – kabichan Mar 18 '16 at 23:24
  • @Jasen It worked! I first thought it was behaving weird but it's because I have a `webgrid` for inline editing in the `listCourses` PartialView. I took out the `webgrid` and tried with a simple table and it worked! – kabichan Mar 18 '16 at 23:43
  • @Jasen I see that the link was answered by you so I will upvote your answer. If you could post your answer here, I will mark it as answer for this question as well. Thank you! – kabichan Mar 18 '16 at 23:44

1 Answers1

0

You have a couple of problems in your document.ready function. 1. You're passing

courseId: datum.id

However, datum object can't be seen anywhere in the javascript function. Maybe you're defining it somewhere else.

  1. instead of alert line I suggest write

    $('#listCourses').html(result);

Also, Remove @{Html.RenderPartial("_CourseList");}, because since _CourseList partial view requires a list model, and you're not providing it during render. So the page will not load.

I could achieve below result with these changes.

enter image description here

Milind Gokhale
  • 575
  • 2
  • 14