DataTable with .Net5 - asp.net-core-mvc

I tried to use datatable with my project and I always got undefined when data return from the controller while I checked the controller already returned 1000 records
this is my controller
[HttpGet]
public JsonResult get_Student_Info()
{
var model = (from C in _db1.ClassesInfos
select new Classes
{
ClassId = C.Id,
ClassCounty = C.ClassCounty ?? "",
ClassLocation = C.ClassLocation,
ClassSize = C.ClassSize ?? 0,
ClassDate = C.ClassDate.ToString(),
//ClassMonitorId = C.MonitorId,
//ClassActive = C.Active ?? 0,
//ClassLastModifedDate = C.LastModifiedDate.ToString(),
//ClassPasscode = C.Passcode,
//ClassType = C.ClassType
}).FirstOrDefault();
return Json(mymodel, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
and this is my view
$(function () {
$.ajax({
type: "GET",
//url: "/Instructor/get_Student_Info",
url: '#Url.Action("get_Student_Info", "Instructor")',
mimeType: 'json',
async: true,
success: function(data) {
$.each(data, function (i, data) {
alert(data.ClassCounty);
alert(data.ClassLocation);
var body = "<tr>";
body += "<td>" + data.ClassCounty + "</td>";
body += "<td>" + data.ClassLocation + "</td>";
body += "</tr>";
$( "#ClasssInfo tbody" ).append(body);
});
/*DataTables instantiation.*/
$( "#ClasssInfo" ).DataTable();
},
});
});

In asp.net mvc, it should be:
Model:
public class Class
{
public string ClassCounty { get; set; }
public string ClassLocation { get; set; }
}
View:
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'ClassCounty' },
{ 'data': 'ClassLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
//must be list model
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In asp.net core/.net 5, it should be:
View:
Note: In asp.net core/.net 5, the response json format is camel case.
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'classCounty' }, //difference here..should be camel case
{ 'data': 'classLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model);
}

Related

Having problems to pass searched data from controller blade file using ajax in laravel

This is my controller method in Admin Controller , this method receive the search input but i am facing problems to pass output data to the view file
public function action(Request $request)
{
if($request->ajax())
{
$students=Student::where('name','LIKE','%'.$request->search."%")->paginate(5);
$data = $students->count();
if($data > 0)
{
$output=$students;
}
else{
$output=$students;
}
return view('search' compact('output'));
}
}
Here is the ajax in view file (search.blade.php)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
// $(document).on('keyup', '#search', function(){
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('search.action')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
Here is the ajax route
Route::get('/search/action', 'AdminController#action')->name('search.action');
Update the below source code.
AdminController.php
public function action(Request $request)
{
if ($request->ajax()) {
// Convert to lowercase after trim the searched text
$search_text = strtolower(trim($request->search));
$students = Student::where('name','LIKE','%'.$search_text."%")->paginate(5);
$data = $students->count();
$output = array();
if ($data > 0) {
$output = $students->toArray();
}
// Return JSON response
return response()->json($output);
}
}
search.blade.php
<input type="text" id="search">
<div id="studentlist">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('search.action')}}',
data:{'search':$value},
success:function(response){
var studentListHtml = "";
if (response) {
if (response.data && response.data.length > 0) {
$.each(response.data , function( index, value ) {
studentListHtml += "<tr><td>" + value.id + "</td>" + "<td>" + value.name + "</td></tr>";
});
$("#studentlist table tbody").empty().html(studentListHtml);
} else {
$("#studentlist table tbody").empty().html("<tr><td colspan='2'>No students found</td></tr>");
}
}
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>

JQuery autocomplete function not loading

I'm working on autocomplete JQuery function to populate student names in the text box. I've utilized every related JQuery library to make the autocomplete function work. When i press F12, it always throws an error which is "autocomplete is not a function". Below is my code that I'm running.
StudentBatch.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
alert("This is autocomplete function");
});
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response) {
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
try {
response($.map(data, function (item) {
return { label: item.StudentName, value: item.StudentName };
}))
} catch (err) { }
}
})
},
messages: {
noResults: "jhh", results: "jhjh"
}
});
});
</script>
StudentController.cs
[HttpPost]
public JsonResult Create(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "fae30ef0-08b2-4490-a389-3c8eb0a7cc53";
var StudentList = user.GetAllUsers().ToList().Where(u => u.FirstName == Prefix && u.usertypeid == stdid).ToString();
return Json(StudentList, JsonRequestBehavior.AllowGet);
}
I have created similar demo which you are creating.
Model
public class CreateUser
{
public string StudentName { get; set; }
public string StudentId { get; set; }
}
Controller
public class StudentController : Controller
{
// GET: Student
public ActionResult Create()
{
return View();
}
[HttpPost]
public JsonResult Create(string prefix)
{
List<CreateUser> studentList = new List<Models.CreateUser>()
{
new CreateUser { StudentId = "1" , StudentName = "Student1"},
new CreateUser { StudentId = "2" , StudentName = "Student2"},
new CreateUser { StudentId = "3" , StudentName = "Student3"},
new CreateUser { StudentId = "4" , StudentName = "Student4"},
new CreateUser { StudentId = "5" , StudentName = "Student5"},
new CreateUser { StudentId = "6" , StudentName = "Student6"},
new CreateUser { StudentId = "7" , StudentName = "Student7"},
};
var searchlist = (from student in studentList
where student.StudentName.Contains(prefix)
select student).ToList();
return Json(searchlist, JsonRequestBehavior.AllowGet);
}
}
View
#model WebApplication6.Models.CreateUser
#{
Layout = null;
}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
.ui-autocomplete-input {
width: 300px;
}
</style>
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.StudentName, value: item.StudentName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
Output

How to use ajax to post Kendo upload files to controller

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

How to get data from controller to view using ajax request - asp.net mvc 4

I am trying to get data from controller to view using ajax but not successfull. Following is my code this is working fine but not getting data. Please help and correct me if i missed something in my code.
Following is my code.
#model MvcAppLearn.Models.Student
<!DOCTYPE html>
<html lang="en">
<head>
<title>This is tile</title>
</head>
<body>
#using (Html.BeginForm("Index", "popup", FormMethod.Get, new { id = "myform" }))
{
<p>
Find by name: #Html.TextBox("SearchString")
<button id="model-opener">Open dialog</button>
</p>
<div id="dialog-model" title="This is title">
<p>
#Html.TextBoxFor(item => item.FirstName, new { id = "ffirst" })<br />
#Html.TextBoxFor(item => item.LastName, new { id = "llast" })<br />
</p>
</div>
}
</body>
</html>
#section script
{
<script>
$(function () {
$("#dialog-model").dialog({
autoOpen: false,
height: 300,
width: 340,
model: true,
show: {
effect: "shake",
duration: 100
},
});
$("#model-opener").click(function (e) {
e.preventDefault();
var txtFirstName = $('#ffirst');
var txtLastName = $('#llast');
var txtSearch = $('#SearchString');
$.ajax({
url: '/popup/Index',
type: 'GET',
data: {
StudentId: txtSearch.val()
},
success: function (data) {
txtFirstName.val(data.FirstName); //HERE IS THE PROBLEM IN GETTING VALUE
txtLastName.val(data.LastName); //HERE IS THE PROBLEM IN GETTING VALUE
$("#dialog-model").dialog("open");
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>
}
Below is my controller
public ActionResult Index(int? StudentId)
{
if (StudentId == null)
{
StudentId = 2;
return View();
}
using (var db = new StdContext())
{
Student std = new Student();
std = db.Students.Where(m => m.StudentId == StudentId).Single();
return View(std);
}
}
You're not returning data, you're returning a view:
return View(std);
If you just want to return the data of the Student object to be consumed by JavaScript code then you probably just want to return it as JSON data:
return Json(std);

passing model from view to controller using jquery

I have a view
#using staffInfoDetails.Models
#model staffInfo
<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
#{staffInfo stf = Model;
}
<div id="education1">
#using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.StaffId)
<table>
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.eduList)
</tr>
<tr>
#*<td><input type="submit" value="create Another" id="addedu"/> </td>*#
#*<td>#Html.ActionLink("Add New", "addNewEdu", new { Model })</td>*#
</tr>
</table>
}
<button id="addedu">Add Another</button>
</div>
I want to pass the model staffInfo to controller using jquery as below
<script type="text/javascript">
$(document).ready(function () {
$("#addedu").live('click', function (e) {
// e.preventDefault();
$.ajax({
url: "Home/addNewEdu",
type: "Post",
data: { model: stf },//pass model
success: function (fk) {
// alert("value passed");
$("#education").html(fk);
}
});
});
});
</script>
the jquery seems to pass only elements not whole model so how can I pass model from the view to the controller so that I don't have to write the whole parameters list in jquery
u can give ID to the form by using this
#using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{
}
Then in the script
<script type="text/javascript">
$('#addedu').click(function(e) {
e.preventDefault();
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: $("#addNewEduForm").serialize(),
success: function(data) {
}
});
}
});
</script>
As I can see you trying to submit form with AJAX? Look at serialize function.
$('#addedu').click(function(e) {
e.preventDefault();
var form = $('form');
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) {
}
});
}
});
You can get your values with getElementById then send your action:
$(document).ready(function () {
var select = document.getElementById('...');
$.ajax({
type: "get",
url: "get_street_name",
data: { a: select },
success: function (data) {
$('#result').html(data);
}
});
}

Resources