I have a project based on ASP.NET MVC4, SQL Server 2012, EF.
In my edit form I need bind dropdown to checkboxes which display on the page. And when checked one or many checkboxes in the dropdown need to loading values from database which according to special rows in table. Here is my code to demonstrate what i have in this moment:
Controller
public ActionResult StudentEdit(int id)
{
Student student = repo.GetStudentById(id);
ViewBag.EducationProgramBachelorId = new SelectList(
context.EducationProgramBachelors, "EducationProgramBachelorId", "ProgramName",
student.EducationProgramBachelorId);
return View(student);
}
public JsonResult ProgramList(int Id)
{
var model = context.EducationProgramBachelors;
var program = from s in model
where s.UniversityId == Id
select s;
return Json(new SelectList(program, "EducationProgramBachelorId", "ProgramName"), JsonRequestBehavior.AllowGet);
}
View
@{
List<ViewModels.AssignedUniversities> universities = ViewBag.Universities;
foreach (var university in universities)
{
<div>
<input type="checkbox"
class="checkboxUniversities"
name="selectedLatUniversities"
value="@university.UniversityNameShort"
@(Html.Raw(university.IsSelected ? "checked=\"checked\"" : ""))/>
@university.UniversityNameShort
</div>
}
}
@Html.DropDownList("EducationProgramBachelorId", String.Empty)
JS Function
$(function () {
$(".checkboxUniversities").change(function () {
$.getJSON('/ControllerName/ProgramList/' + 1, function (data) {
var items = '<option>Select a Program</option>';
$.each(data, function (i, program) {
items += "<option value='" + program.Value + "'>" + program.Text + "</option>";
});
$('#EducationProgramBachelorId').html(items);
});
});
});
I'm stopped on this step in my JS function:
$.getJSON('/ControllerName/ProgramList/' + 1, function (data)
Because I don't know how i can get and send int[] array of my UniversityId and how transform it in the my Json View. Can anybody help me with this situation?
In this line get('/ControllerName/ProgramList/' + 1, 1 - it's a test value to check work or dont work my script.
Between Student and University is many-to-many relationships.
P.S.: Sorry for my English