On my webpage I am displaying a table of data and I want to give the user the ability to sort that data by using a dropdownlist (e.g. By FirstName, By LastName, By State etc...).
I would like to use Ajax to load the sorted data into the data table without a page refresh. I'd also like to use javascript in an unobtrusive way so that the user can still sort if javascript is disabled. This is my first time at trying this approach.
I have been following along with some code in 'ASP.NET MVC In Action' as my template. So far I have:
Webpage
<% using (Html.BeginForm("SortCourseData", "Summary", FormMethod.Post, new { id = "summarysort"})) %>
<% { %>
<div id="sort"><%=Html.DropDownList("SortSelection", Model.sortList, new { onchange="this.form.submit();" })%> </div>
<% } %>
Rendered HTML
<form action="/Summary/SortCourseData" id="summarysort" method="post">
<div id="sort"><select id="SortSelection" name="SortSelection" onchange="this.form.submit();"><option>Incomplete</option>
<option>By first name</option>
<option>By last name</option>
<option>By state</option>
</select> </div>
</form>
Jquery
$('form#summarysort').submit(function(event) {
event.preventDefault();
var sortKey = $("#SortSelection").val();
hijack(this, updateList, sortKey, "html")
});
function hijack(form, callback, sortKey, format) {
$.ajax({
url: '/Summary/SortCourseData',
type: "POST",
data: 'SortSelection=sortKey',
dataType: format,
success: callback
});
}
function updateList(result) {
$('div#datadisplayarea').html(result);
}
Controller
public ActionResult SortCourseData(string SortSelection)
{
SummaryViewModel m = new SummaryViewModel();
SummaryViewData modelData = m.GetViewModelData(SortSelection);
if (Request.IsAjaxRequest())
return PartialView("SummaryCourseList", modelData);
return View("Index", modelData);
}
The issue that I am having is that when I select a sort method in the dropdownlist the submit
event in my jquery does not capture the event. If I put a simple alert();
in the code block I do not get an alert which suggests that it isn't hooking into the form submit event.
How can I successfully hijack the form submit event so that I can use ajax to update my course table? Any guidance would be appreciated...