I'm developing a MVC3 application which interacts with a db. I'm using a form to create an entity and one of the attributes is dependent on another table. To ensure referential integrity, I am populating a drop down list to restrict the user as follows:
var processGroups = repository.getAllProcessGroups();
ViewBag.processGroup_drpdwn = new SelectList(processGroups, "process_group_id", "process_group_name");
return View(); //this is my Creation view
Then, in my View I display the dropdown as
<div class="editor-field">
@Html.DropDownList("groups", (SelectList)ViewBag.processGroup_drpdwn, new { id = "groupsList" })
@Html.ActionLink("Add", "AddGroup", null, new { @class = "addGroupLink" })
</div>
To make things easier on the user, I have implemented a modal dialog using jQuery which allows the user to add an option to the db without having to leave the form to enter it on another page. This all works fine, my Controller returns the partial view, validates the stuff and posts it to the db. Unfortunately, the user has to refresh the page for the new option to get loaded from the db into the drop down list.
I'm trying to update the dropdown list using JSON and JQuery after the insert, but for some reason it is not working.
Additional Info:
Here is the relevant section of the modal form:
@using (Ajax.BeginForm("AddGroup", "Process", null,
new AjaxOptions
{
UpdateTargetId = "update-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess"
}, new { @id = "addGroupForm" }))
Here is a method which returns the groups as a JSON list:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ShowGroups()
{
var groups = repository.getAllProcessGroups();
List<SelectListItem> list=new List<SelectListItem>();
foreach (PROCESS_GROUP p in groups)
{
list.Add(new SelectListItem() { Value = p.PROCESS_GROUP_ID.ToString(), Text = p.PROCESS_GROUP_NAME });
}
return Json(list,JsonRequestBehavior.AllowGet);
}
Here is the jQuery snippet of code which runs after my data has been inserted:
function loadGroups() {
alert();
$.getJSON("/Process/ShowGroups", null, function (data) {
var selectList = $("#groupsList");
selectList.empty();
$.each(data, function (index, optionData) {
var option = $('<option>').text(optionData.Text).val(optionData.Value);
selectList.append(option);
});
});
}
function updateSuccess() {
if ($("#update-message").html() == "True") {
loadGroups();
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Successfully Added");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").show();
}
}
The loadGroups() begins but nothing happens. I also don't get any error messages explaining what went wrong.
UPDATE:
Works now. I had to remove [AcceptVerbs(HttpVerbs.Post)] from the Action