I make a callback jQuery function to fill some collections into my ViewModel with values. When I call this function again, the ViewModel loses the content populated in the first callback.
// ----------------------------------------------------
// ViewModel
public class MyViewModel
{
public string SelectedYear { get; set; }
public IEnumerable<Year> Years { get; set; }
public string SelectedCourse { get; set; }
pulbic IEnumerable<Course> Courses { get; set; }
public string SelectedTeacher { get; set; }
pulbic IEnumerable<Teacher> Teachers { get; set; }
// This constructor is called when I create the ViewModel to pass for View in the "New" Controller method call.
public MyViewModel()
{
Years = new List<Year>() {
new Year(1, '2013'),
new Year(2, '2012')
};
Courses = new List<Course>();
Teachers = new List<Teacher>();
}
// ----------------------------------------------------
// View
@model Application.Models.MyViewModel
<div id="content">
@Html.LabelFor(m => m.SelectedYear)
@Html.DropDownListFor(m => m.SelectedYear, new SelectList(Model.Years, "ID", "Description"))
@Html.Partial("Courses", Model)
@Html.Partial("Teachers", Model)
</div>
// ----------------------------------------------------
// Courses PartialView
<div id="courses">
@Html.LabelFor(m => m.SelectedCourse)
@Html.DropDownListFor(m => m.SelectedCourse, new SelectList(Model.Course, "ID", "Name))
</div>
// ----------------------------------------------------
// Teachers PartialView
<div id="teachers">
@Html.LabelFor(m => m.SelectedTeacher)
@Html.DropDownListFor(m => m.SelectedTeacher, new SelectList(Model.Teachers, "ID", "Name))
</div>
// ----------------------------------------------------
// jQuery function - called when I change the selected year.
$('#SelectedYear').change(function() {
$.get('@Url.Action("MethodToRefreshModel", "Controller")', $('#form').serialize(), function (view) {
$('#content').replaceWith(view);
});
});});
// ----------------------------------------------------
// Controller method to refresh courses
public ActionResult MethodToRefreshCourses(MyViewModel model)
{
model.Courses =
(from course in context.Courses
where course.Year.ID == Convert.ToInt64(model.SelectedYear)
select course).ToList();
// Returning my view with the refreshed model
return View("New", model);
}
// Controller method to refresh teachers
public ActionResult MethodToRefreshTeachers(MyViewModel model)
{
model.Teachers =
(from teacher in context.Teachers
where teacher.Course.ID == Convert.ToInt64(model.SelectedCourse)
select teacher).ToList();
// Returning my view with the refreshed model
return View("New", model);
}
When I call the method to refresh the courses, my page returns and display the correct data. When I selected a course to find the teachers, into my controller my model seems like "lost" the courses filled into the another method. Anyone knows what's happening and how to solve it?
Thank you all!