kabichan
kabichan

Reputation: 1093

MVC C# How to add items to a list in the same view

What I want to do

This is my first MVC project and I want to create a page that allows users to select a course with typeahead and append the selected course to the list of courses. I can save the added course but I'm having trouble figuring out how to display the added course without having to click the refresh button. I'd appreciate any help on how I can achieve this..

enter image description here

What I have

My Classes:

public class CourseList
{
    public int CourseListID {get; set;}
    public List<Course> Courses {get; set}
}
public class Course
{
    public string CourseID {get; set;}
    public string CourseTitle {get; set;}
}
public class CourseListViewModel
{
    public int CourseListID {get; set;}
    public List<Course> Courses {get; set;}  
}

My view (a simpler version):

@using Project.Models.Courses;
@model Project.ViewModels.CourseViewModel


@{Html.RenderPartial("_SelectCourse", new CourseList());}

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

<script type="text/javascript">


$(document).ready(function () {

$('#txtCourse .typeahead').typeahead({
    //setting up typeahead source here
}).on('typeahead:select', function(obj, datum){
    var courseListId = @Model.CourseListID
    $.ajax({
        type: "GET",
        url: "/Course/SaveCourse/",
        data: "",
        data: { courseListId: courseListId, courseId: datum.id },
        success: function () { alert("success");}
    });
});

});



</script>

_CourseInlineEdit.cshtml

@{
    //set up grid here using `Model.Courses`
}

<div id="gridContent">
    //set up grid contents here
</div>

My controller (a simpler version):

public class CourseController : Controller
    {
        public ActionResult Index(int courseListId)
        {
            CourseViewModel data = new CourseViewModel (courseListId);
            return View(data);
        }

        public ActionResult SaveCourse(int courseListId, string courseId)
        {
            new Repository().InsertCourse(courseListId, courseId);

            CourseViewModel data = new CourseViewModel (courseListId);
            return View(data);
            }
            return View();
        }
    }

Upvotes: 1

Views: 3083

Answers (1)

Dispersia
Dispersia

Reputation: 1438

Two options:

  1. Create a partial page for the grid, then just refresh the partial page.

  2. Change your SaveCourse method to return the data you create in index. You can then add a result in your success callback and set your content off the result.

Upvotes: 1

Related Questions