I did spend quite a time figuring out jQuery verbs to do just what I needed. So I’ll share this with my blog and possible readers. On my view I had a model written out, some other stuff, but here I’m only interested in DropDown and JavaScript bits:
@Html.DropDownListFor(m => model.tagId, new SelectList(ViewBag.Tags, "Value", "Text", model.tagId), new {@class = "document-category", data_id = model.modelId})
where
ViewBag.Tags
was populated in controller like this:
ViewBag.Tags = _tagRepository.All
.OrderBy(t => t.Name)
.Select(t => new { Text = t.Name, Value = t.TagId.ToString() })
.OrderBy(t => t.Text)
.ToList();
Back to the view. Added JavaScript like this one:
$(document).on("change", ".document-category", function () {
var select = $(this);
$.ajax({
type: "POST",
url: "@(Url.Action("Action", "Controller"))",
data: { id: select.data("id"),
tagId: $("option:selected", select).val()},
error: function () {
select.after("Error occurred");
},
success: function (data) {
if (data.Success === true) {
select.after(function () {
return $('<div> Saved </div>').delay(1000).fadeOut(1000);
});
} else {
select.after("Error occurred");
}
}
});
});
The very first line can be replaced by $(".document-category").change(function(){
but this time I had to deal with other java-script library that was stripping-bare my stuff. On the other end of the ajax request you need to put controller action:
[HttpPost]
public virtual JsonResult Action(int id, int? tagId)
{
//blah, do some update stuff
return Json(new {Success = true, Message = "Updated"});
}