Menu Case Study Part 5 – Ajax Calls
Prerequisites
Part of Case Study – Menu Example
Summary
In this video we add an AJAX call to our page. It is triggered when a user selects a Menu Group. The final results will display the contents of the menu group. In this example we simply trigger the call to get the results back.
Video
Reference Materials
You should completely review the documentation for the ajax method in jQuery – http://api.jquery.com/jquery.ajax/ this documentation will be very handy to you and also give you all the options available when creating an AJAX call.
Also it is a good idea to start understanding the functions that are provided to you by the HTML helper in RAZOR. This article on Mike’s .NET blog takes you through many of the common overloads of the drop down list – http://www.mikesdotnetting.com/article/128/get-the-drop-on-asp-net-mvc-dropdownlists
FullDetails.cshtml
@model MenuDatabaseCOP4709.Models.Menu
@{
ViewBag.Title = "FullDetails";
}
<script type="text/javascript">
function selectMenuGroup() {
var dd = document.getElementById("MenuGroup");
var index = dd.selectedIndex;
var value = dd.options[index].value;
var text = dd.options[index].text;
alert(index + " : " + value + " : " + text);
$.ajax({
url: '/MenuGroups/GetMenuGroup',
type: 'POST',
datatype: 'json',
data: { id: value },
success: function (data) {
alert("Call was successful " + data)
},
error: function (data) {
alert("Call was unsuccessful " + data)
}
});
}
</script>
<h2>FullDetails</h2>
<div>
<h4>Menu</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.MenuTitle)
</dt>
<dd>
@Html.DisplayFor(model => model.MenuTitle)
</dd>
<dt>
@Html.DisplayNameFor(model => model.MenuDescription)
</dt>
<dd>
@Html.DisplayFor(model => model.MenuDescription)
</dd>
<dt>
Select a Menu Group
</dt>
<dd>
@Html.DropDownList("MenuGroup", new SelectList(Model.MenuGroups,
"MenuGroupId", "MenuGroupTitle"),
new { onchange = "selectMenuGroup()" })
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.MenuID }) |
@Html.ActionLink("Back to List", "Index")
</p>
Method GetMenuGroup() added to MenuGroups controller
public JsonResult GetMenuGroup(string id)
{
MenuGroup menuGroup = db.MenuGroups.Find(Convert.ToInt32(id));
//var json = Json(menuGroup);
return Json(" This will work - but you must serialize your data to Json to process this way " );
}