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) {
}
}
}
Related
So here I want to get the latest data from dbs after uploading a image. with reloading the whole page again. Instead I want only to refresh the image div to show the latest uploaded image. I guess we can use Ajax for this, but I don't have any expertise in ajax so anyone who can help will be glad.
Thank you :)
Here is my code :-----------
.cshtml file
#for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
<li class="list-group-item">
<input asp-for="#Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
<label asp-for="#Model.DailyMenuProducts[i].ProductId"> #Model.DailyMenuProducts[i].ProductName</label>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductId"/>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
#if(#Model.DailyMenuProducts[i].DisplayImage != null)
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<label class="file-label">
<img src="data:image/jpeg;base64,#Model.DailyMenuProducts[i].DisplayImage" width="80" height="80" style="border: 1px solid #000000; cursor:pointer;"/>
</label>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div> }
else
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<a class="file-label btn btn-primary text-white" type="button">
#SharedLocalizer[CashlessCloudConstants.cacheKey_UploadImage]
</a>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div>
}
</li>
}
.js file
$(".file-label").click(function () {
var parent = $(this).parent();
var target = $(parent).find(".productImage");
$(target).click();
});
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
var imagefiles = event.target.files;
var id = event.target.id;
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(imagefiles[0]));
var formData = new FormData();
formData.append("productId", id);
formData.append("productImage", imagefiles[0]);
console.log(formData.getAll("productId"));
console.log(formData.getAll("productImage"));
console.log(imagefiles[0])
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
contentType: false,
processData: false,
data: formData,
method: "POST",
success: function (result) {
window.onbeforeunload = null;
location.reload();
}
});
});
.cs file [Controller Method for AddPhoto]
[HttpPost]
public async Task<IActionResult> AddPhoto([FromForm] DailySelectedProductViewModel dataModel)
{
var userSession = await _userSessionCache.GetUserSessionWithUserIdAsync();
if (dataModel == null)
{
return View("ProductSelection", dataModel);
}
var existing = await _productImageApiService.GetSingleProductImage(userSession.TenantId,dataModel.ProductId);
ProductImages productImage = new ProductImages();
HttpRequest request = HttpContext.Request;
IFormFile file = dataModel.ProductImage;
if (file.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
productImage.ProductImage = imageAsArray;
}
productImage.ProductId = dataModel.ProductId;
}
if (existing.Content != null)
{
await _productImageApiService.Delete(userSession.TenantId,dataModel.ProductId);
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
else
{
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
return Ok();
}
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
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>
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
Hi I tried to save image path in my database and retrieve it to my view to display image using the code below. Which is running perfectly. My problem now is how can I save video file using ajax? I used ajax because I'm not only saving images but I also have different data to save. e.g Name,code,blurb,synopsis etc. Thank you in advance for helping me.
In my view:
<tr>
<td>
Poster Homepage
</td>
<td style>
<form id="file_upload" action="/Movies/UploadFiles" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
#*<div class="progressbar fileupload-progressbar">
</div>*#
<div id="file_name">
</div>
<div id="file_type">
</div>
<div id="file_size">
</div>
<div id="show_image"></div>
<span class="fileinput-button"><a href="javascript:void(0)" class="upload-image">
Upload image</a>
<input type="file" name="files[]" multiple id="file" />
</span>
</div>
</form>
</td>
</tr>
script
$(document).ready(function () {
$('.progressbar').progressbar({ value: 0 });
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
progressall: function (e, data) {
$(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
},
done: function (e, data) {
$('#file_name').html(data.result.name);
$('#file_type').html(data.result.type);
$('#file_size').html(data.result.size);
$('#show_image').html('<img src="/home/image/' + data.result.name + '" />');
$('#file_name').css({ display: 'none' });
$('#file_type').css({ display: 'none' });
$('#file_size').css({ display: 'none' });
//visibility: hidden;
$(this).find('.progressbar').progressbar({ value: 100 });
}
});
Controller:
public FilePathResult Image()
{
string filename = Request.Url.AbsolutePath.Replace("/home/image", "");
string contentType = "";
var filePath = new FileInfo(Server.MapPath("~/Images") + filename);
var index = filename.LastIndexOf(".") + 1;
var extension = filename.Substring(index).ToUpperInvariant();
// Fix for IE not handling jpg image types
contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);
return File(filePath.FullName, contentType);
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadHomePage>();
foreach (string file in Request.Files)
{
HttpPostedFileBase image = Request.Files[file] as HttpPostedFileBase;
if (image.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
image.SaveAs(savedFileName);
r.Add(new UploadHomePage()
{
Name = image.FileName,
Length = image.ContentLength,
Type = image.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookingCMS.Models
{
public class UploadHomePage
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
}
You could pass additional parameters with the FileUpload plugin using the formData setting:
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
formData : {
name: 'this is the name of the movie',
synopsis: 'this is the synopsis of the movie',
type: 'movie'
},
progressall: function (e, data) {
...
},
done: function (e, data) {
...
}
});