I have created a controller with ActionResult Index and created a list of Student class as:
public ActionResult Index()
{
var list = new List<Student>()
{
new Student{Id=1,RegNo="Bcs153048",Name="Ali",Age=21,},
new Student{Id=2,RegNo="Bcs153044",Name="Talha",Age=22,},
new Student{Id=3,RegNo="Bcs153064",Name="Luqman",Age=20,},
new Student{Id=4,RegNo="Bcs153054",Name="Saad",Age=19,},
new Student{Id=5,RegNo="Bcs153036",Name="Hashir",Age=20,},
};
//var jsonString = JsonConvert.SerializeObject(list);
//return View(list);
return Json(list , JsonRequestBehavior.AllowGet);
}
I the view i want to view the list of students in JQuery datatable and i did something like this:
<table id="students" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Registeration No</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
and then below this i have written script as
#section scripts
{
<script>
$(document).ready( function () {
var dataTable = $("#students").DataTable({
ajax: {
url: "/student/index",
dataSrc: "",
},
columns: [
{
data: "Id"
},
{
data: "RegNo",
},
{
data: "Name"
},
{
data: "Age",
}
]
});
});
</script>
}
But i got the Json result when i run the application and navigate to /Student/index wile i want to display list in Jquery datatable :
[{"Id":1,"Name":"Ali","Age":21,"RegNo":"Bcs153048"},{"Id":2,"Name":"Talha","Age":22,"RegNo":"Bcs153044"},{"Id":3,"Name":"Luqman","Age":20,"RegNo":"Bcs153064"},{"Id":4,"Name":"Saad","Age":19,"RegNo":"Bcs153054"},{"Id":5,"Name":"Hashir","Age":20,"RegNo":"Bcs153036"}]
I have added libraries in Bundle.config as:
Libraries in BundleConfig
Add a partial view and add the below script and html table. call that partial view in your main view.
<script>
$(document).ready(function () {
//Call student Details jsonResult Method
$.getJSON("/student/index",
function (json) {
var tr;
//Append each row to html table
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].Id + "</td>");
tr.append("<td>" + json[i].Name + "</td>");
$('table').append(tr);
}
});
});
<table class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>City</th>
<th>Address</th>
</tr>
</thead>
<tbody></tbody>
call the partialview
<div style="margin-top:20px">#Html.Partial("studentDetails");</div>
You said
"i get the Json result when i run the application and navigate to
/Student/index "
...yes, that's correct, because that's what "student/index" returns in your code. But why are you navigating there in your browser directly? It doesn't lead to a view which you can display to the user. It's the ajax call (defined in the DataTables setup) which should request that data. I think maybe you have become confused between the two things.
In your browser you should be navigating to the View which renders the datatable. This will have a separate action method which returns a whole HTML view, not JSON, and thus also has a separate URL from the method which fetches the JSON.
So when you make a HTTP request to the main view in your browser, it loads the view HTML into the browser. Then the JS code on that page runs, loads the DataTable, which triggers the separate HTTP request via ajax to fetch the JSON data.
For example:
"Student" controller:
//load the view
[HttpGet]
public ActionResult Index()
{
return View();
}
//load the JSON
[HttpGet]
public JsonResult GetStudentList()
{
var list = new List<Student>()
{
new Student{Id=1,RegNo="Bcs153048",Name="Ali",Age=21,},
new Student{Id=2,RegNo="Bcs153044",Name="Talha",Age=22,},
new Student{Id=3,RegNo="Bcs153064",Name="Luqman",Age=20,},
new Student{Id=4,RegNo="Bcs153054",Name="Saad",Age=19,},
new Student{Id=5,RegNo="Bcs153036",Name="Hashir",Age=20,},
};
return Json(list , JsonRequestBehavior.AllowGet);
}
"Student/Index" View:
<table id="students" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Registration No</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts
{
<script>
$(document).ready( function () {
var dataTable = $("#students").DataTable({
ajax: {
url: '#Url.Action("GetStudentList", "student")', //note the use of a HTML helper to generate the correctly routed URL, and also the change of action name to "GetStudentList"
dataSrc: "",
},
columns: [
{
data: "Id"
},
{
data: "RegNo",
},
{
data: "Name"
},
{
data: "Age",
}
]
});
});
</script>
}
Related
I am trying to read my query from controller and I already have the Ajax call to get it through my button. but my problem is there is no changes happening on my index view, the table hasn't change and can't figure out why.
Here is my View:
#{
ViewBag.Title = "LoadInfo";
}
#model IEnumerable<MyApp.Models.LoadInfo>
<html>
<body>
<input style="text-align:left; width:250px" id="txtSearch" type="text" />
<button type="button" id="search" onclick="search()" class="btn btn-primary">Search</button>
<div class="tableFixHead" ; style="margin-top: 10px;">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.ID</td>
<td>#item.Name</td>
<td>#item.Address</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
<script>
function search() {
var search = document.getElementById("txtSearch").value
$.ajax({
url: '/Home/LoadInfo',
type: 'GET',
data: {
'name': search
},
success: function (data) {
alert("success")
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
Controller:
public ActionResult LoadInfo(string name)
{
List<readDetails> userDetails = new List<readDetails>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT ID, Name, Address FROM EmpDetails WHERE Name like '%" + name + "%' LIMIT 500";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
userDetails.Add(new readDetails
{
op = sdr["ID"].ToString(),
op_desc = sdr["Name"].ToString(),
doc_id = sdr["Address"].ToString(),
});
}
}
con.Close();
}
}
return View(userDetails);
}
I also using this controller to my starting page load not sure if this is cause of the problem, do I need to create a separate controller and view for initial loading and for my search functionality.
The result alerts me to "success" but its weird because my table is not changing or refreshing just like if you do a simple query with filter from query browser.
You need to add html() function for table's <tbody> element to override existing results with the new one:
$.ajax({
url: '/Home/LoadInfo',
type: 'GET',
data: {
'name': search
},
success: function (data) {
alert("success");
$('.table tbody').html(data); // override previous results
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
If the response contains entire <table> element, you should omit tbody selector:
$('.table').html(data);
Also you might try to return PartialView(), e.g. return PartialView(userDetails); instead of entire view page if the search results are provided in same search page.
Update:
Since the data returns entire HTML page, the current controller action should be modified to return JSON response like this example:
public ActionResult LoadInfo(string name)
{
List<readDetails> userDetails = new List<readDetails>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT ID, Name, Address FROM EmpDetails WHERE Name like '%" + name + "%' LIMIT 500";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
userDetails.Add(new readDetails
{
op = sdr["ID"].ToString(),
op_desc = sdr["Name"].ToString(),
doc_id = sdr["Address"].ToString(),
});
}
}
con.Close();
}
}
return Json(userDetails, JsonRequestBehavior.AllowGet);
}
Then, replace existing <tbody> contents with data from response:
$.ajax({
url: '/Home/LoadInfo',
type: 'GET',
data: {
'name': search
},
dataType: 'json',
success: function (data) {
alert("success");
var tblbody = $('.table').find('tbody');
tblbody.empty(); // remove existing rows
var row = '';
$.each(data, function(i, item) {
row += $('<tr>').append($('<td>').text(item.ID), $('<td>').text(item.Name), $('<td>').text(item.Address));
tblbody.append(row); // add new rows
});
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
At this point the search results should appear on the same table instead of returning entire HTML content.
am creating one project am using angularjs. I want to get the data from database.i had try this code but we are not getting the data also not getting any error in console. after put the debugger in javascript its successfully run
so please give your feedback.
in my controller am using the code
public JsonResult userList()
{
dBase dal = new dBase();
var userlist = dal.GetAllUsers("0");
return Json(userlist, JsonRequestBehavior.AllowGet);
}
<link href="~/css/custom.css" rel="stylesheet">
<script src="~/js/AngularJS.js"></script>
<script src="~/js/angular.min.js"></script>
<script src="~/js/Module.js"></script>
<script src="~/js/Service.js"></script>
<script src="~/js/WolskiDevJ.js"></script>
in module
var app = angular.module("myApp", []);
in Service.js
app.service("myService", function ($http) {
this.getAlluser = function () {
debugger;
try {
return $http.get("users/userList");
}
catch (err) {
return err;
}
};
});
in WolskiDevJ.js
app.controller("UserCntrl", function ($scope, myService) {
getalluserlist();
function getalluserlist() {
debugger;
var getuserdata = myService.getAlluser();
debugger;
getuserdata.then(function (usr) {
$scope.userlist = usr.data;
}, function () { alert('get error') });
};
});
in view am using the code like
<script src="~/js/AngularJS.js"></script>
<script src="~/js/angular.min.js"></script>
<script src="~/js/Module.js"></script>
<script src="~/js/Service.js"></script>
<script src="~/js/WolskiDevJ.js"></script>
<div class="static_pages home" ng-app="myApp" ng-controller="UserCntrl">
<table id="myTable" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="8%">Name</th>
<th width="20%">Email</th>
<th width="12%">Username</th>
<th width="14%">Access</th>
<th width="8%">Status</th>
<th width="6%">Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="userlist in ulist">
<td>{{userlist.first_name}} </td>
</tr>
</table>
</div>
Instead of
<tr ng-repeat="userlist in ulist">
<td>{{userlist.first_name}} </td>
</tr>
type
<tr ng-repeat="myUser in userlist">
<td>{{myUser.first_name}} </td>
</tr>
I have a List view with list of task. Each task have state(Active, Stoped, Complete etc). For displaying states I use EnumDropDownListFor.
View code:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.TaskText)
</td>
<td>
#Html.DisplayFor(modelItem => item.TillDate)
</td>
<td>
#Html.EnumDropDownListFor(modelItem => item.State)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
And Task class:
public class Task
{
public int Id { get; set; }
public string TaskText { get; set; }
public DateTime TillDate { get; set; }
public TaskState State { get; set; }
}
public enum TaskState
{
Active=0,
Stoped,
Complete
}
Now I want to change task state on this view. I mean, I want to select state from dropdown and after selection changed, using ajax, call controller action to save it to database.
How can I do this using ajax?
UPD:
I'v tryed something like this, but can;t figure out how to get task id:
function FillCity() {
var stateId = $('#State').val();
// var taskId=???
$.ajax({
url: '/Home/Edit',
type: "POST",
dataType: "JSON",
data: { State: stateId, taskId: id}
});
}
});
}
The way you tried is absolutely correct, so for the one thing to get the task id, you can make use of hidden variable to store the id and get through javascript like below.
Your changed code:
I'v tryed something like this, but can;t figure out how to get task id:
function FillCity() {
var stateId = $('#State').val();
var taskId=$('#hdntaskid').val()
$.ajax({
url: '/Home/Edit',
type: "POST",
dataType: "JSON",
data: { State: stateId, taskId: id}
});
}
});
}
View Code:
#foreach (var item in Model) {
<tr>
<td>
#Html.HiddenFor(model => model.Id,
new { id= "hdntaskid", Value = #Model.Id})
<td>
<td>
#Html.DisplayFor(modelItem => item.TaskText)
</td>
<td>
#Html.DisplayFor(modelItem => item.TillDate)
</td>
<td>
#Html.EnumDropDownListFor(modelItem => item.State)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
Alternate Js Code:
$(document).ready(function()
{
$("#State").on("change", function()
{
var stateId = $(this).val();
var taskid = $(this).parent().siblings().find('#hdntaskid');
$.ajax({
url: '/Home/Edit',
type: "POST",
dataType: "JSON",
data: { State: stateId, taskId: id}
});
});
});
Hope above information was helpful
thanks
Karthik
You can listen to the change event on the SELECT element, read the selected value and and send it to server (an action method) via ajax where you can save it.
Since we need the task id as well, Let's keep that in data attribute of the SELECT element. We will also use the Url.Action helper method to generate the correct relative path to the server action method which will be called from the ajax code and will save values.
#Html.EnumDropDownListFor(modelItem => item.State, new { data_taskid=item.Id,
data_url=Url.Action("SaveStatus")})
This will render the SELECT element with data attribute "taskid" and "url" ( See the generated html markup by checking the "view source" of the page)
Now the javascript to listen to the change event and make the ajax call
$(function(){
$("SELECT[name='State']").change(function() {
var taskId=$(this).data("taskid");
var stateId=$(this).val();
$.post($(this).data("url"),{ task : taskId, state : stateId},function(re){
// to do : Do something once ajax call is successful
});
});
});
Assuming that you have an action method called SaveStatus which has 2 parameters, task and state
[HttpPost]
public ActionResult SaveStatus(int task,int state)
{
// TO DO : Save the data using the values of task and state
return Json(new { status="success"});
}
**This is ajax function**
$.ajax({
type : "Get",
url : url,
data:$("#client").serialize(),
dataType:'json',
success : function(response)
{
},
error : function(e)
{
alert('Error: ' + e);
}
});
This is my Controller
#RequestMapping(value = "/authenticate/ajaxObj", method = RequestMethod.GET)
public #ResponseBody ArrayList<String> ajax_Claims(Model model,
#ModelAttribute("CalculatorDO") CalculatorDO calculatorDO)
{
System.out.println("\nAjax Hit the Controller");
ArrayList<String> clist=new ArrayList<>();
ArrayList<String> namelist=new ArrayList<>();
ArrayList<String> classlist=new ArrayList<>();
ArrayList<String> address=new ArrayList<>();
namelist=calculatorDO.getNameList();
classlist=calculatorDO.getNameList();
address=calculatorDO.getNameList();
clist.add(namelist);
clist.add(classlist);
clist.add(address);
model.addAttribute("nameList", clist);
return clist;
}
My table
<table>
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>address</th>
</tr>
</thead>
<tbody>
<c:forEach items="${nameList}" var="list">
<tr>
<td><c:out value="${list.namelist}"/></td>
<td><c:out value="${list.classlist}" /></td>
<td><c:out value="${list.address}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
I want to reload the table.
Replace <tbody> with
<tbody id="ajax-tbody-results">
</tbody>
And use jQuery tmpl to fill the table with your data (jQuery tmpl )
<script id="table-template" type="text/x-jquery-tmpl">
<tr>
<td>${namelist}</td>
<td>${classlist}</td>
</tr>
</script>
$.ajax({
type : "Get",
url : url,
dataType:'json',
success : function(response)
{
jQuery("#table-template").tmpl(data).appendTo("#ajax-tbody-results");
},
error : function(e)
{
alert('Error: ' + e);
}
});
I'm having problem with binding JSON from ASP.net webform webapi to the viewmodel with KnockoutJs. There is no problem with wepapi and mapping to mappedQuickEntries.
Where did I get it wrong? Thanks.
Error:
Error: Unable to parse bindings.
Message: ReferenceError: ItemPartNumb is not defined;
Bindings value: value: ItemPartNumb
View:
<div>
<table border="1" cellpadding="0" cellspacing="0">
<tbody data-bind="foreach: quickEntries">
<tr>
<td data-bind="value: ItemPartNumb"></td>
<td data-bind="value: ItemDescription"></td>
</tr>
</tbody>
</table>
ViewModel:
<script type="text/javascript">
var QuickEntry = function(_itemPartNumb, _itemDescription) {
this.ItemPartNumber = ko.observable(_itemPartNumb);
this.ItemDescription = ko.observable(_itemDescription);
};
function QuickEntriesViewModel () {
var self = this;
self.quickEntries = ko.observableArray([]);
$.ajax({
url: '/DesktopModules/Blah/API/Data/GetTenQuickEntries',
type: 'GET',
dataType: 'json',
success: function (data) {
var mappedQuickEntries = $.map(data, function (item) {
return new QuickEntry(item.ItemPartNumb, item.ItemDescription);
});
self.quickEntries(mappedQuickEntries);
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
};
ko.applyBindings(new QuickEntriesViewModel());
ItemPartNumb vs ItemPartNumber
And you are using the value-binding instead of the text-binding.
http://jsfiddle.net/MizardX/9sqvk/