When I loading table I got ajax error in datatable.(.net)
This is my data table code
<table id="productsTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th>Price</th>
<th>No of Products</th>
</tr>
</thead>
</table>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />
#section scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('#productsTable').DataTable({
"ajax": {
"url": "/Products/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Code" },
{ "data": "Price" },
{ "data": "Available" }
]
});
});
</script>
}
this is my controller
public ActionResult GetData()
{
using (DBModel db = new DBModel())
{
List<product> proList = db.products.ToList<product>();
return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
}
}
product is my db table ,
this is the model
public partial class product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public decimal Price { get; set; }
public Nullable<int> Available { get; set; }
public byte[] is_deleted { get; set; }
}
Error Looks like
DataTables warning: table id=productsTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Click here: https://dotnetfiddle.net/S7KWOg
I did not get an error with this:
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index4</title>
#*added this css*#
<style>
body {
padding-left: 50px;
width: 80%;
}
</style>
#*removed the bootstrap for better dataTable styling*#
#*putting all your scripts in the head*#
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
#*<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />*#
#*added this script*#
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
#*need this jquery script*#
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
#*<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>*#
<script>
$(document).ready(function () {
$('#productsTable').DataTable({
"ajax": {
//using home controller instead of products
"url": "/Home/GetData",
//"url": "/Products/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Code" },
{ "data": "Price" },
{ "data": "Available" }
]
});
});
</script>
</head>
<body>
<table id="productsTable" class="table table-striped table-bordered display">
#*added display class*#
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th>Price</th>
<th>No of Products</th>
</tr>
</thead>
</table>
#section scripts{
#*moved these scripts to the head*#
}
</body>
</html>
Controller/Model
public class product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public decimal Price { get; set; }
public Nullable<int> Available { get; set; }
public byte[] is_deleted { get; set; }
}
public class HomeController : Controller
{
public ActionResult GetData()
{
//using (DBModel db = new DBModel())
//{
// List<product> proList = db.products.ToList<product>();
// return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
//}
List<product> proList = new List<product>{ new product { Available = 1, Code = "Code1", is_deleted = new byte[1],
Name = "Name1", Price = 1.27M, ProductId = 1 },
new product { Available = 2, Code = "Code2", is_deleted = new byte[2],
Name = "Name2", Price = 1.28M, ProductId = 2 },
new product { Available = 3, Code = "Code3", is_deleted = new byte[3],
Name = "Name3", Price = 1.29M, ProductId = 3 } };
return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
}
public ActionResult Index4()
{
return View();
}
Related
Banging my head against a brick wall here. I have a Datatable that is populated by GET call to an api from a dropdown box. Ideally i want the user to select an option in the dropdown and the table will reload with the data from the call.
The api is getting called and data is being returned with each selection but the table doesnt display the data or get refreshed like i would expect.
CheckIn.cshtml
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "CheckIn";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CheckIn</h2>
<div class="form-group">
#Html.DropDownList("Customers",
new SelectList(Model, "Id", "Name"), "Please select a customer",
new { #class = "form-control", #id = "customers"})
</div>
<table id="rentals" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts
{
<script>
$(document).ready(function () {
var customerId;
var table = $("#rentals").DataTable({
ajax: {
type: 'GET',
url: '/api/RentalsApi/',
data: function (d) {
d.id = customerId ? customerId : -1;
},
dataSrc: ""
},
columns: [
{
data: "name"
}
]
});
$('#customers').on('change', function (e) {
console.log(this.value);
customerId = this.value;
table.ajax.reload();
});
});
</script>
}
API
// GET /api/RentalsApi/{1}
[HttpGet]
public IHttpActionResult GetRental(int id)
{
if (id == -1) return Json(new System.Web.Mvc.EmptyResult());
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
return Ok(customer);
}
Customer Model
using System;
using System.ComponentModel.DataAnnotations;
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter customer's name.")]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsletter { get; set; }
public MembershipType MembershipType { get; set; }
[Display(Name = "Membership Type")]
public byte MembershipTypeId { get; set; }
[Display(Name = "Date of Birth")]
[Min18YearsIfAMember]
public DateTime? Birthdate { get; set; }
}
}
Just make your ajax api call as normal and then use this to redraw the table
table=$("#rentals").DataTable()
table.clear().rows.add(newData).draw(); //newData is the data you get from your ajax call
View
<script type="text/javascript">
$(document).ready(function () {
$("#getRates").click(function () {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetDetail", "ControllerName")',
data: {}
}).success(function () {
alert("hit!")
$('#MyTable').load(location.href + " #MyTable")
});
});
});
</script>
<button type="button" id="getRates" class="button getRates">Get Rates</button>
<br /><br /><br />
<table id="MyTable">
<tr>
<th width="15%">Name</th>
<th width="15%">Address</th>
<th width="15%">City</th>
<th width="15%">State</th>
</tr>
<tr>
<td>#GetRateModel.OriginName</td>
<td>#GetRateModel.OriginAddress</td>
<td>#GetRateModel.OriginCity</td>
<td>#GetRateModel.OriginState miles</td>
</tr>
<tr>
<td>#GetRateModel.DestName</td>
<td>#GetRateModel.DestAddress</td>
<td>#GetRateModel.DestCity</td>
<td>#GetRateModel.DestState miles</td>
</tr>
</table>
Controller Functions
[HttpPost]
public ActionResult GetDetail(string origin, string destination, string billTo, bool flat, bool rpm)
{
GetRateModel total = new GetRateModel
{
OriginName = "Name",
OriginAddress = "Address",
OriginCity = "City",
OriginState = "State",
DestName = "Name",
DestAddress = "Address",
DestCity = "City",
DestState = "State",
};
return PartialView("Index", total);
}
Model
public class GetRateModel
{
public string OriginName { get; set; }
public string OriginAddress { get; set; }
public string OriginCity { get; set; }
public string OriginState { get; set; }
public string DestName { get; set; }
public string DestAddresss { get; set; }
public string DestCity { get; set; }
public string DestState { get; set; }
This works when I declare static variables in my model, but I need to set these to an instance of the class instead. How would I wire my table to update based on an instance of my model? I've seen a solution that creates rows with a foreach loop and lists in the model, but I don't think that would be the best solution for my problem.
You need to update your view as following:
#* try specifying the fully qualified name of your Model class here if the following line gives error *#
#model GetRateModel
<script type="text/javascript">
$(document).ready(function () {
$("#getRates").click(function () {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetDetail", "ControllerName")',
data: { origin: "", destination: "", billTo: "", flat: true, rpm: true }
}).success(function () {
alert("hit!")
//$('#MyTable').load(location.href + " #MyTable")
$('#MyTable').html(response);
});
});
});
</script>
<button type="button" id="getRates" class="button getRates">Get Rates</button>
<br /><br /><br />
<div id="MyTable">
#if (Model != null)
{
<table>
<tr>
<th width="15%">Name</th>
<th width="15%">Address</th>
<th width="15%">City</th>
<th width="15%">State</th>
</tr>
<tr>
<td>#Model.OriginName</td>
<td>#Model.OriginAddress</td>
<td>#Model.OriginCity</td>
<td>#Model.OriginState miles</td>
</tr>
<tr>
<td>#Model.DestName</td>
<td>#Model.DestAddress</td>
<td>#Model.DestCity</td>
<td>#Model.DestState miles</td>
</tr>
</table>
}
</div>
For more information: https://learn.microsoft.com/en-us/aspnet/mvc/overview/views/dynamic-v-strongly-typed-views
Also, I strongly suggest that you use a different View file to render the table data otherwise whenever you click on the button, your final html in browser will contain repeated script tags and repeated buttons.
This is our Home Index:
#model ELearning.Data.ELearningEgitimDTO
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
#if (TempData["message"] != null)
{
<div class="alert alert-info" role="alert">#TempData["message"]</div>
}
<div>
<div>
#if (Model.EgitimTuru == 5)
{
<h1>Yangın Eğitimi</h1>
}
<table class="table table-responsive">
<tr>
<td width="20%">Şirket Adı:</td>
<td width="80%">#Model.Name</td>
</tr>
<tr>
<td>Eğitimi Veren:</td>
<td>#Model.PersonelAdi</td>
</tr>
<tr>
<td>Eğitim Tarihi:</td>
<td>#Model.Tarih</td>
</tr>
</table>
</div>
<div>
<table class="table table-responsive">
<tr>
<td>Eğitim Konuları:</td>
</tr>
#foreach (var konu in Model.Adi)
{
<tr>
<td><ul><li>#konu</li></ul></td>
</tr>
}
</table>
</div>
</div>
<p class="text-right"><button onclick="getStartDate()" class="btn btn-primary btn-lg ">Eğitime Başla »</button></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function getStartDate() {
$.post("/Video/GetStartDate",
{
PerNr: #Model.PerNr,
StartDate: "",
EndDate: "",
EgitimFilesId: #Model.FileId
});
}
</script>
</div>
This is Video Index:
#model WebApplication3.Models.VideoLogsModel
#{
ViewBag.Title = "Video Page";
}
<div class="jumbotron">
<div>Eğitime başlanan zaman:</div>
<div id="startdate"></div>
<div class="col-md-12 text-center">
<video controls controlslist="nodownload" id="videoPlayer" width: 100% height: auto>
<source src="~/Video/GetVideo" type="video/mp4">
</video>
</div>
<br />
<div class="text-right">
<p id="button" onclick="egitimiBitir()" class="btn btn-danger btn-lg ">Eğitimi Bitir</p>
</div>
<script type="text/javascript">
var vid = document.getElementById("videoPlayer");
var button = document.getElementById("button");
if (vid.played) {
setInterval(function () { vid.pause(); }, 30000);
}
vid.addEventListener("ended", function() {
button.className = "btn btn-success btn-lg "
});
function egitimiBitir() {
if (vid.ended) {
$.post("/Video/GetEndDate",
{
PerNr: #Model.PerNr,
StartDate= "",
EndDate: "",
EgitimFile sId: #Model.EgitimFilesId
});
}
else {
document.getElementById("message").innerHTML = "Video tamamlanmadan eğitimi bitiremezsiniz.."
}
}
</script>
</div>
This is our main model:
public class ELearningEgitimDTO
{
public ELearningEgitimDTO() { }
public ELearningEgitimDTO(string PerNr, int ID)
{
this.ID = ID;
this.PerNr = PerNr;
}
public int ID { get; set; }
public string PerNr { get; set; }//katılımcıID
public string Name { get; set; }//şirket adı
public int EgitimTuru { get; set; }
public DateTime Tarih { get; set; }//egitim tarihi
public string PersonelAdi { get; set; } // eğitimi veren
public int FileId { get; set; }
public string FileName { get; set; }
public string[] Adi { get; set; }
}
This is our model:
public class VideoLogsModel
{
public int EgitimFilesId { get; set; }
public int PerNr { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
This is our Home Controller:
public class HomeController : Controller
{
public ActionResult Index(int EgitimId=4, string PerNr="2")
{
ELearningService service = new ELearningService();
ELearningEgitimDTO egitim = new ELearningEgitimDTO(PerNr, EgitimId);
return View(service.getInfo(egitim)); //eğitim bilgileri istenirken egitimId ve egitim kullanıcıdaki eğitmenin perNr si verilmeli!!
}
}
This is our Video Controller:
public class VideoController : Controller
{
public ActionResult Index(VideoLogsModel model)
{
return View(model);
}
public ActionResult GetVideo()
{
var memoryStream = new MemoryStream(System.IO.File.ReadAllBytes(#"C:\Users\cyare\Desktop\videoplayback.mp4"));
//byte[] bytes = System.IO.File.ReadAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4");
//System.IO.File.WriteAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4", bytes);
return new FileStreamResult(memoryStream, "video/mp4");
}
/* [HttpPost]
public ActionResult GetStartEndDate(VideoLogsModel logs)
{
DateTime startDate = logs.StartDate; //database de uygun tabloya yazılır
return RedirectToAction("Index", "Video");
}*/
[HttpPost]
public ActionResult GetStartDate(VideoLogsModel model)
{
model.StartDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.startDate = model.StartDate;
ELearningService service = new ELearningService();
//service.CreateLogs(user);
//return RedirectToAction("Index","Video",model);*/
return RedirectToAction("Index", model);
}
[HttpPost]
public ActionResult GetEndDate(VideoLogsModel model)
{
model.EndDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.endDate = model.EndDate;
ELearningService service = new ELearningService();
service.UpdateLogs(user);
TempData.Add("message", String.Format("Eğitiminiz Tamamlanmıştır!"));
return RedirectToAction("Index", "Home");
}
}
My question is how can i pass the model from home index to video controller and then to video index?
Video Index doesn't run. It goes to video index but then it runs home index again.
Also it runs egitimibitir() function before button's onclick function.
You send an ajax request to your service. (endpoint => GetEndDate) I think you can change your code like that,
$.ajax({
type: "POST",
url: "/Video/GetEndDate", //your reqeust url
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
// your data here
}),
success: function (data) {
// check state of data
// after check window.location = // redirect url
},
error: function (data) {
// handle exception
}
});
You can change your controller method to a data controller. (not an ActionResult. create a custom result object which include your data and your success state. you can use this custom result object every ajax requests for return state and data). If an exception occurs while executing "GetEndDate" method, you need to handle exception and you need to show it to client. You send exception or your success complete response to to client(view). (you can handle your exception data in ajax error: function)
Hello I am facing problems with doing my first webclient working with jquery AJAX JSON
Actually if I am pressing submit at my webclient to add a contact to a contact List it is not doing anything for me someone can help me here?
If am using postman to send a request it is working but the informations doesnt display in the index (videolist [html]) it is just showing as usual text in
/url/{id}
This is my HTML
<!DOCTYPE html>
<html>
<head>
<title>Contact Archiv HTML</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript"
src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript" src="ajaxfunctions.js"></script>
</head>
<body>
<div class="centerdiv">
<header><h1>Video Archiv</h1></header>
<section class="left">
<h1>Neues Video anlegen</h1>
<p>
<form id="newVideo">
<label>id:</label>
<input type="text" name="id" required="required" >
<label>vorname:</label>
<input type="text" name="vorname" required="required" >
<label>nachname:</label>
<input type="text" name="nachname" required="required" >
<label>anrede:</label>
<input type="text" name="anrede" required="required" >
<label>adresse:</label>
<textarea name="adresse" required="required" rows="10"></textarea>
<label>telefon:</label>
<input type="text" name="telefon" required="required">
<label>email:</label>
<input type="text" name="email" required="required">
<label>handy:</label>
<input type="text" name="handy" required="required" >
<br>
<input type="submit" id="newVideoButton">
</form>
</p>
</section>
<section class="right">
<h1>Meine Videos</h1>
<p>
<button id="loadtable">Laden</button>
<table id="videotable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>vorname</th>
<th>nachname</th>
<th>anrede</th>
<th>adresse</th>
<th>telefon</th>
<th>email</th>
<th>handy</th>
</tr>
</thead>
</table>
</p>
</section>
<footer>Tested</footer>
</div>
</body>
</html>
This is my ajaxfunction:
//On Page load - register listeners and load existing videos in datatable
$(document).ready(function() {
loadDataTable();
//process the form newVideo
$("#newVideo").submit(function(event) {
postVideo(event);
});
//Load Datatable
$('#loadtable').click(function() {
loadDataTable();
});
});
function postVideo(event) {
// get the form data
var formData = {
'id' : $('input[name=id]').val(),
'vorname' : $('textarea[name=vorname]').val(),
'nachname' : $('input[name=nachname]').val(),
'anrede' : $('input[name=anrede]').val()
'adresse' : $('input[name=adresse]').val(),
'telefon' : $('textarea[name=telefon]').val(),
'email' : $('input[name=email]').val(),
'handy' : $('input[name=handy]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to
use (POST for our form)
contentType : 'application/json',
url : '/kontakte', // url where we want to POST
data : JSON.stringify(formData), // data we want to POST
success: function( data, textStatus, jQxhr ){
loadDataTable();
},
error: function( jqXhr, textStatus, errorThrown ){
console.log(errorThrown);
}
});
// stop the form from submitting the normal way and refreshing the
page
event.preventDefault();
}
function loadDataTable() {
var table = $('#videotable').DataTable({
destroy: true,
"ajax": {
"url": "/kontakte", //URL
"dataSrc": "" // Cause of flat JsonObjects
},
"columns": [
{ "data": "id" },
{ "data": "vorname" },
{ "data": "nachname" },
{ "data": "anrede" },
{ "data": "adresse" },
{ "data": "telefon" },
{ "data": "email" },
{ "data": "handy"}
]
});
}
Class Contact:
package RestPackage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
public class Kontakte {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String vorname;
private String nachname;
private String anrede;
private String adresse;
private String telefon;
private String email;
private String handy;
public Kontakte() {}
public Kontakte(int id, String vorname, String nachname, String anrede,
String adresse, String telefon, String email, String handy) {
super();
this.id = id;
this.vorname = vorname;
this.nachname = nachname;
this.anrede = anrede;
this.adresse = adresse;
this.telefon = telefon;
this.email = email;
this.handy = handy;
}
public long getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public String getAnrede() {
return anrede;
}
public void setAnrede(String anrede) {
this.anrede = anrede;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getTelefon() {
return telefon;
}
public void setTelefon(String telefon) {
this.telefon = telefon;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHandy() {
return handy;
}
public void setHandy(String handy) {
this.handy = handy;
}
}
My Controller:
package RestPackage;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import RestPackage.Kontakte;
#RestController
public class VerwaltungsController {
#Autowired
VerwaltungsService verwaltungsService;
#RequestMapping ("/kontakte")
public List<Kontakte> getKontakteList(){
return verwaltungsService.getKontakteList();
}
#RequestMapping("/kontakte/{id}")
public Kontakte getKontakt(#PathVariable Integer id) {
return verwaltungsService.getKontakt(id);
}
#RequestMapping(method=RequestMethod.POST, value="/kontakte")
public void addKontakt(#RequestBody Kontakte k) {
verwaltungsService.addKontakt(k);;
}
#RequestMapping(method=RequestMethod.PUT, value="/kontakte/{id}")
public void updateKontakt(#PathVariable Integer id, #RequestBody Kontakte
kontakt) {
verwaltungsService.updateKontakt(id, kontakt);
}
#RequestMapping(method=RequestMethod.DELETE, value="/kontakte/{id}")
public void deleteKontakt(#PathVariable Integer id) {
verwaltungsService.deleteKontakt(id);
}
}
Service Class:
package RestPackage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import RestPackage.Kontakte;
#Service
public class VerwaltungsService {
#Autowired
private KontakteRepository kontakteRepository;
public List<Kontakte> getKontakteList() {
ArrayList<Kontakte> mylist= new ArrayList<>();
Iterator<Kontakte> it = kontakteRepository.findAll().iterator();
while(it.hasNext())
mylist.add(it.next());
return mylist;
}
public Kontakte getKontakt(#PathVariable Integer id) {
return kontakteRepository.findOne(id);
}
public void addKontakt(#RequestBody Kontakte kontakt) {
kontakteRepository.save(kontakt);
}
public void updateKontakt(#PathVariable Integer id, #RequestBody Kontakte
kontakt) {
Kontakte k = kontakteRepository.findOne(id);
k.setVorname(kontakt.getVorname());
k.setNachname(kontakt.getNachname());
k.setAdresse(kontakt.getAdresse());
k.setAnrede(kontakt.getAnrede());
k.setEmail(kontakt.getEmail());
k.setHandy(kontakt.getHandy());
k.setTelefon(kontakt.getTelefon());
kontakteRepository.save(k);
}
public void deleteKontakt(#PathVariable Integer id) {
kontakteRepository.delete(id);
}
}
CrudRep. Interface:
package RestPackage;
import org.springframework.data.repository.CrudRepository;
import RestPackage.Kontakte;
public interface KontakteRepository extends CrudRepository<Kontakte,
Integer> {
}
There is , missing in the mapping of the input properties. I also advice you to start using the console (key F12) to debug the code and discover problems easly.
I want to show table data using Ajax request.
Here is my Ajax Syntax:
$(document).ready(function() {
var table = $("#attendance").DataTable({
ajax: {
url: '#Url.Action("GetAttendance", new {id = Model.Student.Id})',
dataSrc: ""
},
columns: [
{
data: "Date",
render: function(data) {
return data;
}
},
{
data: "Status.StudentStatus",
render: function(data) {
return data;
}
}
]
});
Here is my action method:
public JsonResult GetAttendance(int id)
{
var studentAttendance = _context.Attendances.ToList().Where(m => m.StudentId == id);
return Json(studentAttendance, JsonRequestBehavior.AllowGet);
}
Now, where am I wrong?
Please plug in the following example. If you don't mind, please just follow my example, and then you will be able to fix your issue.
Controller/Model:
public class AjaxViewModel
{
public string theDate { get; set; }
public string StudentStatue { get; set; }
}
public class HomeController : Controller
{
public string GetAttendance()
{
AjaxViewModel aViewModel = new AjaxViewModel { StudentStatue = "stat4", theDate = "12/24/2005" };
AjaxViewModel aViewModel2 = new AjaxViewModel { StudentStatue = "stat5", theDate = "12/24/2005" };
AjaxViewModel aViewModel3 = new AjaxViewModel { StudentStatue = "stat6", theDate = "12/24/2005" };
IList<AjaxViewModel> data = new List<AjaxViewModel>();
data.Add(aViewModel);
data.Add(aViewModel2);
data.Add(aViewModel3);
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(data);
json = "{ \"data\": " + json;
json = json + " }";
return json;
}
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2020</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function () {
$("#uiDataTable").DataTable({
"ajax": '#Url.Action("GetAttendance")',
columns: [
{
"data": "theDate"
},
{
"data": "StudentStatue"
}
]
});
})
</script>
</head>
<body>
<table id="uiDataTable" class="display table table-striped table-bordered">
<thead>
<tr>
<th>
Date
</th>
<th>
Status
</th>
</tr>
</thead>
</table>
</body>
</html>