Ajax each function response is blank - ajax

I am doing search a product example using spring and ajax.I try to display the result using each function in a table. But getting blank response with headings being displayed. On firebug response field shows [].
Controller
#RequestMapping(value="searchproduct", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody List<Product> searchProduct(#RequestBody #RequestParam(required=false, defaultValue="productName") String productName,
Map model) {
List<Product> productResults = productService.searchProductByName(productName);
return productResults;
}
DAOImpl
public List<Product> searchProductByName(String productName) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Product.class);
criteria.add(Restrictions.ilike("productName", "%"+productName+"%"));
return criteria.list();
}
ServiceImpl
#Transactional
public List<Product> searchProductByName(String productName) {
return productDAO.searchProductByName(productName);
}
JSP
<script type="text/javascript">
$(document).ready(function() {
$('#searchForm').submit(function(event) {
var productName = $('#productName').val();
var json = { "productName" : productName };
$.ajax({
url: $("#searchForm").attr( "action"),
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(productResults) {
$('#searchTable').
append("<thead><tr><th>Product Name</th><th>Price</th></tr></thead>");
$('#searchTable').append("<tbody>");
var tableContent = "";
$(productResults).each(function(index, product){
tableContent +=
'<tr><td> ' +
product.productName+' </td><td> ' +
product.price+' </td></tr>';
});
$('#searchTable').append(tableContent);
$('#searchTable').append("</tbody>");
}
});
event.preventDefault();
});
});
</script>
<form id="searchForm" action="searchproduct.json" >
Product Name: <input type="text" name="productName" value="${product.productName}"
id="productName" />
<input type="submit" value="Search" />
</form>
<div id="formResponse">
<table id="searchTable">
</table>
</div>

Related

Aspnet Core - Error 400 When i send Httpost with js

I need to get a list permissao when I select a group, I made the methods but when I select the group, it returns me an error.
PermissaoGrupo/ObterPermissoesAdd:1 Failed to load resource: the
server responded with a status of 400 ()
View
#model RKMES.Models.ViewModel.PermissaoGrupoViewModel
<script type="text/javascript" src="assets/js/plugins/forms/inputs/duallistbox.min.js"></script>
<script type="text/javascript" src="assets/js/pages/form_dual_listboxes.js"></script>
<h2>Index</h2>
<div class="form-group">
#*<label asp-for="Grupos" class="control-label">Grupo</label>*#
#*<select class="custom-select custom-select-sm" asp-items="#(new SelectList(Model.Grupos,"Id","Nome"))"></select>*#
Grupos
#Html.DropDownList("Grupos", new SelectList(Model.Grupos,"Id", "Nome"))
</div>
<!-- Filtered results -->
<div class="panel panel-flat">
<div class="panel-heading">
<h5 class="panel-title">Filtered results</h5>
</div>
<div class="panel-body">
#*<select multiple="multiple" class="form-control listbox-no-selection" asp-items="#(new SelectList(Model.Permissoes,"Id","Nome"))"></select>*#
#Html.DropDownList("Permissoes", new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Nome"))
</div>
</div>
<!-- /filtered results -->
<script type="text/javascript">
$(document).ready(function () {
$('#Grupos').change(function () {
var idGrupo = $('#Grupos').val();
if (idGrupo > 0) {
$.post('#Url.Action("ObterPermissoesAdd", "PermissaoGrupo")', { 'idGrupo': idGrupo }, function (data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$('#Permissoes').append('<option value="' +data[i].Id+ '">' + data[i].Nome+ '</option>');
}
}
});
}
});
});
</script>
PermissaoGrupoController
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ObterPermissoesAdd(int idGrupo)
{
return Json(_grupoContext.GetPermissoesAdd(idGrupo));
}
GrupoService
public async Task<List<Permissao>> GetPermissoesAdd(int id)
{
return await _context.Grupo_Permissao_Permissao
.Where(x => x.Grupo_PermissaoId == id)
.Select(x => x.Permissao)
.ToListAsync();
}
Model
namespace RKMES.Models
{ // essa é uma tabela intermediaria das entidades Grupo_Permissao e Permissao
public class Grupo_Permissao_Permissao
{
public int Id { get; set; }
public int Grupo_PermissaoId { get; set; }
public int PermissaoId { get; set; }
public virtual Grupo_Permissao Grupo_Permissao { get; set; }
public virtual Permissao Permissao { get; set; }
}
}
What am I doing wrong?
For your issue, it is caused by ValidateAntiForgeryToken. which will check whether the request contains RequestVerificationToken header.
For a quick test, you could remove [ValidateAntiForgeryToken] from Controller.
For a recommended way, you need to attach the anti forgery token like
<script type="text/javascript">
$(document).ready(function(){
var Group = {
GroupId: 1,
GroupName: "My Group Name"
};
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
headers: {
"RequestVerificationToken": gettoken()
},
data: JSON.stringify(data)
});
}
</script>

How to delete multiple rows of database using ajax and spring mvc

I want to delete multiples rows using ajax and spring mvc but it always delete just one row.
//code controller
#RequestMapping(value = "/rmvclientserviceajax", method = RequestMethod.POST)
#ResponseBody
public void rmvclintServiceajax (HttpServletRequest request, Model model)
{
for(String serviceID: request.getParameterValues("idService"))
{ Long clientID = (long) Integer.parseInt(request.getParameter("idClient"));
metiersr.deleteClientToService(clientID,(long) Integer.parseInt(serviceID));}
}
//code js
function AjaxPostdelete() {
if ($('#idService').prop('checked')) {
var idService = $('#idService').val();
var idClient = $('#idClient').val();
$.ajax({
type : "POST",
url : "/cp/client/rmvclientserviceajax",
data : "idClient=" + idClient + "&idService=" + idService,
success : function(response) {
{
{
}
}
// code html
<form>
<ul class="liste_servch">
<input type="hidden" id="idClient" value="${client.idPersonne}" />
<c:forEach items="${listservclt}" var="servclt">
<li>
<input id="idService" type="checkbox" value="${servclt.idService}" />
<c:out value="${servclt.nomService}" />
</li>
</c:forEach>
</ul>
<input type="button" value="supp" onclick="AjaxPostdelete() ">
</form>
Try following;)
function AjaxPostdelete() {
var idServiceObjs = $('input[id=idService]');
var idServices = [];
for (var i = 0; i < idServiceObjs.length; i++) {
if(idServiceObjs[i].prop('checked')) {
idServices.push(idServiceObjs[i].value);
}
}
var idClient = $('#idClient').val();
$.ajax({
type : "POST",
url : "/cp/client/rmvclientserviceajax",
data : {idClient:idClient,idService:idServices},
success : function(response) {
}
}
}

Kendo-Knockout reference with MVC using Database First Approach [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am looking for Kendo-Knockout reference with MVC using Database First Approach.
Please look at my code below,
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.Category = ko.observable();
self.Price = ko.observable();
var Product = {
Id: self.Id,
Name: self.Name,
Category: self.Category,
Price: self.Price
};
self.Product = ko.observable();
self.Products = ko.observableArray();
$.getJSON("/Product/GetProoducts", function (data) {
self.Products(data);
$.each(data, function (index) {
})
});
self.Create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.push(data);
self.Name("");
self.Price("");
self.Category("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
}
ko.applyBindings(new ViewModel());
});
I am getting an issue with the above code. I need to do CRUD operation using kendo - knockout js.
Please find below code ,
Repository
interface IProductRepository : IDisposable
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
void Save();
}
public class ProductRepository : IProductRepository, IDisposable
{
RepositoryEntities context = null;
public ProductRepository()
{
context = new RepositoryEntities();
}
public ProductRepository(RepositoryEntities context)
{
this.context = context;
}
public IEnumerable<Product> GetAll()
{
return context.Products.ToList();
}
public Product Get(int id)
{
return context.Products.Find(id);
}
public Product Add(Product item)
{
Product newProduct = context.Products.Add(item);
int id = context.SaveChanges();
return newProduct;
}
public bool Update(Product item)
{
context.Entry(item).State = EntityState.Modified;
context.SaveChanges();
return true;
}
public bool Delete(int id)
{
Product objProduct = context.Products.Find(id);
context.Products.Remove(objProduct);
context.SaveChanges();
return true;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Controller
public class ProductController : Controller
{
// private IProductRepository productRepository;
private IProductRepository repository = new ProductRepository();
//public ProductController(IProductRepository repository)
//{
// this.productRepository = repository;
//}
//
// GET: /Product/
public ActionResult Index()
{
return View();
}
public JsonResult GetProoducts()
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
public JsonResult AddProduct(Product item)
{
item = repository.Add(item);
return Json(item, JsonRequestBehavior.AllowGet);
}
public JsonResult EditProduct(int id, Product product)
{
product.Id = id;
if (repository.Update(product))
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
return Json(null);
}
public JsonResult DeleteProduct(int id)
{
if (repository.Delete(id))
{
return Json(new { Status = true }, JsonRequestBehavior.AllowGet);
}
return Json(new { Status = false }, JsonRequestBehavior.AllowGet);
}
}
View
#{
ViewBag.Title = "Index";
}
<script src="~/jquery.min.js"></script>
<script src="~/kendo.all.min.js"></script>
<script src="~/knockout-3.1.0.js"></script>
<script src="~/knockout-kendo.min.js"></script>
<link href="~/kendo.silver.min.css" rel="stylesheet" />
<div id="body">
<h2>Kendo Knockout CRUD Operations</h2>
<div data-bind="kendoGrid: { data : Products, rowTemplate: 'rowTmpl', scrollable: true, sortable: true, useKOTemplates: true}">
</div>
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: Category"></td>
<td> <button data-bind="click: $root.Edit">Edit</button></td>
<td> <button data-bind="click: $root.Delete">Delete</button></td>
</tr>
</script>
<br/>
<div data-bind="if: Product">
<div>
<h2>Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">ID</label>
<label data-bind="text: Product().Id, visible: false"></label>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.Update">Update</button>
<button data-bind="click: $root.Cancel">Cancel</button>
</div>
</div>
<br />
<div data-bind="ifnot: Product()">
<div>
<h2>Add New Product</h2>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: $root.Name" type="text" title="Name" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<div>
<label for="category">Category</label>
<input data-bind="value: $root.Category" type="text" title="Category" />
</div>
<div>
<button data-bind="click: $root.Create">Save</button>
<button data-bind="click: $root.Reset">Reset</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.Category = ko.observable();
self.Price = ko.observable();
var Product = {
Id: self.Id,
Name: self.Name,
Category: self.Category,
Price: self.Price
};
self.Product = ko.observable();
self.Products = ko.observableArray();
$.getJSON("/Product/GetProoducts", function (data) {
self.Products(data);
$.each(data, function (index) {
})
});
self.Create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.push(data);
self.Name("");
self.Price("");
self.Category("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
self.Reset = function () {
self.Name("");
self.Price("");
self.Category("");
}
// Edit product details
self.Edit = function (Product) {
self.Product(Product);
}
// Cancel product Details
self.Cancel = function () {
self.Product(null);
}
//Update Product Details
self.Update = function () {
var Product = self.Product();
$.ajax({
url: '#Url.Action("EditProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.removeAll();
self.Products(data); //Put the response in ObservableArray
self.Product(null);
alert("Record Updated Successfully");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
}
//Delete Product Details
self.Delete = function (Product) {
if (confirm('Are you sure to Delete "' + Product.Name + '" product ??'))
{
var id = Product.Id;
$.ajax({
url: '/Product/DeleteProduct/'+ id,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(id),
success: function (data) {
self.Products.remove(Product);
}
}).fail(
function (xhr, textStatus, err) {
self.status(err);
});
}
}
}
ko.applyBindings(new ViewModel());
});
</script>
Please find below links too,
http://www.dotnet-tricks.com/Tutorial/knockout/0bOU010413-Knockout-CRUD-Operations-using-MVC4.html
http://pinaki-mukherjee.blogspot.in/2013/01/kendo-knockout-grid-bind.html
http://www.c-sharpcorner.com/uploadfile/yusufkaratoprak/asp-net-mvc-with-knockout-js/
http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in

update model with ajax in razor

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have masterpage.in picture u see what happen.
this is my code
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
<div class="btnContainer">
delete
<br />
<br />
</div>
<script>
$(function () {
// function for delet info and update #updateAjax div
$("#DeleteUser").click(function (event) {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
$.ajax({
url: '#Url.Action("DeleteUser", "UserManagement")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: JSON.stringify(list),
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
// window.location.reload()
},
error: function (data) {
//$('#updateAjax').html(data);
window.location.reload()
}
}); //end ajax
});});
</script>
</form>
this my controller code
public ActionResult View1()
{
ViewBag.PageTittle = "user list";
ViewBag.FormTittle = "user list";
SetUserManagement();
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(Result.Data);
}
else
{
return View(new VwUser());
}
}
public ActionResult DeleteUser(string[] userId)
{
SetUserManagement();
string message = "", CssClass = ""; ;
foreach (string item in userId)
{
//TODO:show Message
var Result = userManagement.DeleteUser(int.Parse(item));
if (Result.Mode != Common.Extensions.ActionResultMode.Successfully)
{
var messageResult = XmlReader.FindMessagekey(Result.Mode.ToString());
message += messageResult.MessageContent + "<br/>";
CssClass = messageResult.cssClass;
}
}
if (string.IsNullOrEmpty(message))
{
SetMessage(Common.Extensions.ActionResultMode.Successfully.ToString());
}
else
{
ViewBag.MessageResult = message;
ViewBag.cssClass = CssClass;
}
//
{
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View("~/Views/UserManagement/View1.cshtml", Result.Data);
}
else
{
return View("~/Views/UserManagement/View1.cshtml", new VwUser());
}
}
}
It looks to me that your view ViewUserList.cshtml is using a Layout that would either be set through Layout or through the _ViewStart.cshtml file. Make sure you're not using any of these.
For disabling the use of your Layout, you could take a look at this question. Or just set Layout = null

mvc - binding JSON object

I am following a simple video tutorial for Knockout.js by Steve Sanderson:
http://channel9.msdn.com/Events/MIX/MIX11/FRM08
At the very end of it he performs an AJAX call to show how can you use knockout to process data on the server. I repeat all of what he is doing, but for some reason my JSON object doest bind to a POCO class correctly. This is an object I send from the view:
{"firstName":"Bartosz","lastName":"Malinowski","friends":[{"name":"Zofia"},{"name":"Zenon"}],"fullName":"Bartosz Malinowski"}
and then use this code to read it in the controller:
public JsonResult Save(Person person)
{
var message = string.Format("Saved {0} {1}", person.firstName, person.lastName);
return Json(new { message });
}
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string fullName { get; set; }
public ICollection<Friend> friends { get; set; }
}
public class Friend
{
public string Name { get; set; }
}
}
My code on the client side looks like this:
'#{
ViewBag.Title = "Home Page";
}
<script src="../../Scripts/jquery.tmpl.js" type="text/javascript"></script>
<p>First name: <input data-bind="value: firstName"/></p>
<p>Last name: <input data-bind="value: lastName"/></p>
<p>Full name: <span data-bind="text: fullName"></span></p>
<h2>Friends (<span data-bind="text: friends().length"></span>)</h2>
<ul data-bind="template: { name: 'friendsTemplate', foreach: friends }"></ul>
<script id="friendsTemplate" type="text/html">
<li>
<input data-bind="value: name"/>
<button data-bind="click: remove">Remove</button></li>
</script>
<button data-bind="click: addFriend, enable: friends().length < 5">Add Friend</button>
<button data-bind="click: save">Save</button>
<script type="text/javascript">
function friend(name) {
return {
name: ko.observable(name),
remove: function () {
viewModel.friends.remove(this);
}
};
}
var viewModel = {
firstName: ko.observable("Bartosz"),
lastName: ko.observable("Malinowski"),
friends: ko.observableArray([new friend("Zofia"), new friend("Zenon")]),
addFriend: function () {
this.friends.push(new friend("Jan"));
},
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type: "post",
data: ko.toJSON(this),
contenttype: "application/json",
success: function (result) { alert(result.message) }
});
}
};
viewModel.fullName = ko.dependentObservable(function () {
return this.firstName() + " " + this.lastName();
}, viewModel);
ko.applyBindings(viewModel);
</script>
When I run it in debug mode and check person in the Save method parameter I've got null value for each Person property. So it just doesn't bind to me??
I do exactly the same here is my code
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: ko.toJSON(viewModel),
contentType: 'application/json; charset=utf-8',
success: function (returnedData)
{
window.location.replace(urlRedirect);
}
});
There is a few differences : dataType and the charset, I'd say that it's the dataType.
I also have the [HttpPost] on my action.

Resources