MVC 4 Razor using Ajax forms to update a foreach loop
@VishalVaishya presents the right idea, but there's a simpler way, which doesn't involve custom javascript code: AjaxOptions has an UpdateTargetId property that the AJAX toolkit will interpret to mean you want the given target to be updated with the results sent back from the controller.
FindATeacher.cshtml:
@using (Ajax.BeginForm("FilterTeachers", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "TeacherList" })){ ...}<hr /><div id="TeacherList"> @Partial("TeacherList", Model.Teachers)</div>
TeacherList.cshtml
@model IEnumerable<Teacher>@foreach(var teacher in Model){ ...}
Controller action:
[HttpPost] public ActionResult FilterTeachers(String teacherName, String instrumentID, String cityID) { Model.Teachers = TeacherService.GetTeacherList(teacherName, instrumentID, cityID); return PartialView("TeacherList", Model.Teachers); }
You can try following method:
Separate your foreach loop into another partial view. And load your partial view on filter / click event and pass filtered parameters to your controller-action.
JS change event code will be something like this:
var teacherName = ''; //get your selected teachernamevar instrumentID = ''; //get your selected instrumentidvar cityID = ''; //get your selected city idvar url = '@Url.Action("FilterTeachers", "ControllerName", new { teacherName = "teacher-Name", instrumentID="instrument-ID", cityID="city-ID" })';url = url.replace("teacher-Name", teacherName).replace("instrument-ID", instrumentID).replace("city-ID", cityID);$('#result').load(url);