How to show JSON data in Jquery DataTables using “Ajax source
User655436493 posted
Hi….
I have a view in which user will select the dropdown and hits the button to get the data. I need to show this data in Jquery Datatables.
How can i get the data to show it in DataTable. This is my below sample JSON data coming from my request in Controller.
{“Status”:true,”ErrorCode”:0,”TimeStamp”:”/Date(1311951697070)/”,”Messages”:[“Total 2 user(s) returned.”],
“Data”:
[
{“UserName”:”AAA”,
“Email”:”aaa@test.com“},
{“UserName”:”BBB”,
“Email”:”bbb@test.com“}]}
Here is my code for Contrioller and View:
[HttpPost] public JsonResult Index(RoleViewModel role) { var rolecode = role.RoleCode; if (rolecode == "all") rolecode = string.Empty; if (!ModelState.IsValid) { return Json("Invalid"); } WebRequest request = WebRequest.Create("https://abc.com/useraccount/getusers.json?Rolecode="+rolecode); request.Method = "GET"; //Basic Http Authentication string username = "test"; string pwd = "CEE589B1-C438-4673-94F6-FB3E6D4634D2"; string authInfo = username + ":" + pwd; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers["Authorization"] = "Basic " + authInfo; WebResponse response = request.GetResponse(); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); ViewBag.Response = responseFromServer; return Json(responseFromServer, JsonRequestBehavior.AllowGet); }View:
@model DirectAccess.Models.RoleViewModel @{ ViewBag.Title = "UserInfo"; } @using (Html.BeginForm("Index", "UserInfo", FormMethod.Post, new { id="UserInfo"})) { @Html.ValidationSummary(true) <h2> Get User Information:</h2> <br /> <br /> <div id="Role"> <h2> Select User Role</h2> <br /> <label id="viewbag">@ViewBag.Response</label> <br /> <br /> @Html.LabelFor(m => m.RoleCode): @Html.DropDownListFor(m => m.RoleCode, new SelectList(new DirectAccess.Models.RoleViewModel().GetRoles(), "Value", "RoleCode"), "Select") @Html.ValidationMessageFor(m => m.RoleCode) <input type="submit" id="GetUserBtn" value="Get Users" /> <table id="mytable"> </table> <script type="text/javascript"> $(function () { $("#GetUserBtn").click(function (e) { e.preventDefault(); var postUrl = $("#UserInfo").attr("action"); var roleCode = $("#RoleCode").val(); $.post(postUrl, { "roleCode": roleCode }, function (data) { data = $.parseJSON(data); console.log(data.Data); $('#mytable').dataTable({ "aaData": data, "aoColumns": [{ "mDataProp": "UserName" }, { "mDataProp": "Email"}] }); }); return false; }); }); </script> </div> }
Thanks
Read more here: Source link