This is a last attempt for me to get some insight on this issue before I scratch JqGrid all together. I have a col in my colModel to upload an Image. I am using ajaxfileupload. Although there are several of the same examples out there they seem to work for others but mine is not. When I select an Image from the enctype: "multipart/form-data" for some reason it is not putting anything in the record for the object. I have a few breakpoints and when I view the data everything is visible but the product Image. So all fields are there and ProductImage is null. It is like JqGrid is not holding the object and passing it. Since it is null, nothing gets uploaded either. Maybe I am missing something but I have looked through my code over and over again and it appears to be just like what I have read in examples that supposedly work.
Any help with would be fantastic as I am ready to scratch this and use something else.
Below is my code for the process. sections only. if you need to see other code let me know.
JqGrid:
{
name: "ProductImage",
index: "ProductImage",
mtype: "Post",
editable: true,
editrules: { required: true },
edittype: "file",
search: true,
resizable: false,
width: 210,
align: "left",
editoptions: {
enctype: "multipart/form-data"
}
},
.....
{
// edit option
zIndex: 100,
url: "/Admin/EditProducts",
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterSubmit: uploadImage,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
....
function uploadImage(response, postdata) {
//debugger;
//var json = $.parseJSON(response.responseText);
//if (json) return [json.success, json.message, json.id];
//return [false, "Failed to get result from server.", null];
var data = $.parseJSON(response.responseText);
if (data.success == true) {
if ($("#ProductImage").val() != "") {
ajaxFileUpload(data.id);
}
}
return [data.success, data.message, data.id];
}
function ajaxFileUpload(id) {
$.ajaxFileUpload(
{
url: "/Admin/UploadImage",
secureuri: false,
fileElementId: "ProductImage",
dataType: "json",
data: { id: id },
success: function (data, status) {
if (typeof (data.isUploaded) != "undefined") {
if (data.isUploaded == true) {
return;
} else {
alert(data.message);
}
}
else {
return alert("Failed to upload image!");
}
},
error: function (data, status, e) {
return alert("Failed to upload image!");
}
}
)
return false;
}
Controller:
public string EditProducts(Product product)
{
string msg;
try
{
if (ModelState.IsValid)
{
using (StoreEntities db = new StoreEntities())
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
}
else
{
msg = "Did not save! ";
}
}
catch (DbEntityValidationException ex)
//catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
foreach (var validationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
System.Diagnostics.Debug.WriteLine("Property: {0} Error: {1}",
validationError.PropertyName, validationError.ErrorMessage);
}
}
}
return msg;
}
....
#region Upload Images
[HttpPost]
public JsonResult UploadImage(HttpPostedFileBase ProductImage)
{
string directory = "~/Images/";
if (ProductImage != null && ProductImage.ContentLength > 0)
{
var fileName = Path.GetFileName(ProductImage.FileName);
ProductImage.SaveAs(Server.MapPath(Path.Combine(directory, fileName)));
//ProductImage.SaveAs(Path.Combine(directory, fileName));
}
return Json(new { isUploaded = true, message = "Uploaded Successfully" }, "text/html");
}
#endregion
Related
i have problem to return two parameters result from return json in c# .net 5 to ajax. where the return result cannot be read in ajax
i have html code
<button id="DELETE" onclick="ConfirmDelete(#item.Id)" class="btn btn-danger btn-sm">Delete</button>
jquery code
function ConfirmDelete(id) {
Swal.fire({
icon:'question',
title: 'are you sure delete it?',
showCancelButton: true,
confirmButtonText: 'Ya',
confirmButtonColor: '#d33',
cancelButtonText: 'Tidak'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
type: 'POST',
url: '#Url.Content("Latihan/Delete")',
data: { Id: id },
dataType: "json",
success: function (data) {
if (data.Isuccess == true) {
Swal.fire({
icon: 'success',
title: 'Delete Success',
text: '',
confirmButtonText: 'Ok'
}).then((result) => {
if (result.isConfirmed) {
location.reload();
}
});
}
else {
Swal.fire({
icon: 'error',
title: 'Error Found',
text: data,
confirmButtonText: 'Ok'
}).then((result) => {
if (result.isConfirmed) {
location.reload();
}
});
}
},
error: function (data) {
Swal.fire({
icon: 'error',
title: 'Unknown Error',
text: 'Delete Failed',
confirmButtonText: 'Ok'
}).then((result) => {
if (result.isConfirmed) {
location.reload();
}
});
}
});
}
})
};
controller
[HttpPost]
public async Task<JsonResult> Delete(int? id)
{
List<string> msgerror = new List<string>();
bool result = false;
try
{
if (id == null || id < 0)
{
msgerror.Add("Data cannot be null");
}
else
{
var LatihanDelete = await _context.TB_BIODATA.FirstOrDefaultAsync(e => e.Id == id);
if (LatihanDelete == null)
{
msgerror.Add("Data not found");
}
else
{
//_context.TB_BIODATA.Remove(LatihanDelete);
//await _context.SaveChangesAsync();
result = true;
}
}
}
catch (Exception e)
{
msgerror.Add("Error Exception : " + e.Message);
}
return Json(new{Isuccess = result, MessageError = msgerror});
}
but if I pass only one parameter, then the return result can be read fine in ajax
controller
return Json("Success");
jquery code
success: function (data) {
if (data == "Success") {
Swal.fire({
icon: 'success',
title: 'Delete Success',
text: '',
confirmButtonText: 'Ok'
}).then((result) => {
if (result.isConfirmed) {
location.reload();
}
});
}
can anyone help why this is different, and what should i fix? thank you
try this
return new JsonResult( new {IsSuccess = result, MessageError = msgerror} );
I have an appointments application with multiple users who can multiple appointments. I display this on FullCalendar.
However, I'm having a problem. I want the User logged in to see their events and not others. This works when I close the application completely but if I log out and want to login as another user, I see the other users appointments.
I tried using re fetch events with FullCalendar then I looked at the Configuration.ProxyCreationEnabled = false; within my DAL class.
Here's my controller method:
public JsonResult GetEvents()
{
string username = Membership.GetUser().UserName;
var getAdmin = (from a in db.Admins
where username == a.AdminUsername
select a.AdministrationId).SingleOrDefault();
var events = (from a in db.Appointments
where getAdmin == a.AdministrationId
select a).ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And FullCalendar:
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Appointments/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
details: v.DetailsOfAppointment,
date: moment(v.DateOfAppointment),
room: v.RoomType,
confirmed: v.Confirmed,
colour: v.ThemeColour,
church: v.Church.Name,
parishAdminName: v.Admins.AdministratorName,
parishAdminUser: v.Admins.AdminUsername,
parishAdminId: v.Admins.AdministratorId,
fee: v.Fee,
id: v.AppointmentId
});
})
GenerateCalender(events);
},
error: function (error) {
alert("failed");
console.log(error);
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar('refetchEvents');
$('#calender').fullCalendar({
contentHeight: 500,
defaultDate: new Date(),
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
timeFormat: 'HH:mm',
eventLimit: true,
eventColor: events.ThemeColour,
events: events,
eventRender: function (event, element) {
if (event.fee == null) {
if (event.confirmed == false) {
element.css('background-color', '#FF0000');
element.css('border-color', '#FF0000');
}
else {
element.css('background-color', '#008000');
element.css('border-color', '#008000');
}
}
else
{
element.css('background-color', '#0000FF');
element.css('border-color', '#0000FF');
}
},
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #details').text(calEvent.details);
var $details = $('<div/>');
if (calEvent.fee != null) {
$details.append($('<p/>').html('<b>Date of Ceremony : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
}
else {
$details.append($('<p/>').html('<b>Date of Appointment : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
}
if (calEvent.end != null) {
$details.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$details.append($('<p/>').html('<b>Details : </b>' + calEvent.details));
$details.append($('<p/>').html('<b>Church Name : </b>' + calEvent.church));
if (calEvent.fee == null) {
if (calEvent.room != null) {
$details.append($('<p/>').html('<b>Room : </b>' + calEvent.room));
}
else {
$details.append($('<p/>').html('<b>Room Not Confirmed'));
}
}
$details.append($('<p/>').html('<b>Parish Admin : </b>' + calEvent.parishAdminName));
if (calEvent.confirmed == true)
{
$details.append($('<p/>').html('<b>Status : Confirmed </b>'));
}
else
{
$details.append($('<p/>').html('<b>Status : Not Confirmed </b>'));
}
$('#myModal #pDetails').empty().html($details);
$('#myModal').modal();
}
})
}
})
</script>
}
Your JSON payload is likely being cached by the browser.
To stop this, add this attribute above GetEvents:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
to disable caching.
I have a photo which I can upload to sever in my project and info about my photo store in database. This is how record in my database looks like:
Id:1 , Path: ~/Upload/d8cd7f97-1da2-43f3-b43a-74e5c9f28731.JPG DispayName: 9.jpg , IsMainImage:True , FurnitureId:25 .
So here is my method which delete file from server and database:
[HttpPost]
public JsonResult DeleteFile(int Id)
{
try
{
FurnitureImages furnitureImages = db.FurnitureImages.Find(Id);
if (furnitureImages == null)
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return Json(new { Result = "Error" });
}
//Remove from database
db.FurnitureImages.Remove(furnitureImages);
db.SaveChanges();
//Delete file from the file system
var path = Server.MapPath(furnitureImages.Path);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
In my view I pass parametr to ajax:
<script type="text/javascript">
$('.deleteItem').click(function (e) {
e.preventDefault();
var $ctrl = $(this);
if (confirm('Do you really want to delete this file?')) {
$.ajax({
url: '#Url.Action("DeleteFile")',
type: 'POST',
data: { Id: $(this).data('Id') }
}).done(function (data) {
if (data.Result == "OK") {
$ctrl.closest('li').remove();
}
else if (data.Result.Message) {
alert(data.Result.Message);
}
}).fail(function () {
alert("There is something wrong. Please try again.");
})
}
});
</script>
And finally call this function:
#for (int i = 0; i < Model.SecondaryImages.Count; i++)
{
#Html.HiddenFor(m => m.SecondaryImages[i].Id)
#Html.HiddenFor(m => m.SecondaryImages[i].Path)
#Html.HiddenFor(m => m.SecondaryImages[i].DisplayName)
<img src="#Url.Content(Model.SecondaryImages[i].Path)" />
X
}
Model in this example is ViewModel. But it doesn't work , It writes me "There is something wrong. Please try again" , first condition If doesn't work, what's wrong? Thanks
Okay , problem was solved , my Id was null , so error was in this line
data: { Id: $(this).data('Id') }
It must be
data: { Id: $(this).attr('data-Id') }
now we get right id and image will be delete from server and file system
On my View I have a button I use to submit a [description] value to my Controller via JSON, which is then used to create a new Table record. For example:
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
}
What I'd like to do now (before saving the Status to the DB) is run a check to see if any other records in the INV_Statuses table have a [description] value matching the one submitted to the function for new creation. If there is a match, I want to return an error/validation? message and alert the user the submitted value already exists and to choose it from the DropDownList on the View.
Can anyone provide an example of how to go about this with LINQ in my MVC Controller?
EDIT: Added my View JS code for submitting the new Status:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
EDIT2:
Adricadar's suggestion:
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
if (isDuplicateDescription)
{
ModelState.AddModelError("Error", "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.");
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
I added a .ToUpper() in my comparison in Controller, but even though the match with .ToUpper() gets identified, the ModelState.AddModelError() code fires, then the code returns and no error message is issued?
The value (though duplicate) still gets added to the dropdownlist (visually, not in DB) via my current JS code:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
Check for existing status and set status back as follows:
var existingStatus = db.INV_Statuses.FirstOrDefault(s => s.status_description == description);
if (existingStatus ==null)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
else
{
// set the status back to existing
status = existingStatus;
}
Set an existing flag in your response:
return Json(new { ID = status.Id, Text = status.status_description, AlreadyExists = (existingStatus != null) }, JsonRequestBehavior.AllowGet);
Then in your response JavaScript, simply parse out the returned data:
success: function (resp) {
if (resp.AlreadyExists != true)
{
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
else
{
alert(resp.status_description + " already exists");
$("#selectStatus").val(resp.Id);
}
}
You can query the database for a status with an existing description and if exists and an model state error.
Be aware that string comparison is case sensitive.
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
string error = String.Empty;
if (isDuplicateDescription)
{
error = "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.";
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description, Error = error , IsDuplicate = isDuplicateDescription }, JsonRequestBehavior.AllowGet);
}
In javascript verify if response have IsDuplicate = true if is true you skip the part where you need to add an element in dropdown.
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
if(resp.IsDuplicate)
{
//display error from response
//display resp.Error
} else {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
},
error: function () {
alert("ERROR!");
}
});
});
hiii to all, i am using jqgrid, and want to display error message if the user wants to delete the truck record which is in use, i have to display a error message truck in use..
here is my jqgrid:-
jQuery(document).ready(function () {
var grid = jQuery("#TrucksGrid141");
grid.jqGrid({
url: '/Admin/GetTrucksForJQGrid',
datatype: 'json',
mtype: 'Post',
cellsubmit: 'remote',
cellurl: '/Admin/SaveTruck',
height: '100%',
pager: '#pagerTrucks',
colNames: ['Id', 'Name', ''],
colModel: [
{ name: 'Id', index: 'Id', key: true, hidden: true, editrules: { edithidden: true } },
{ name: 'Name', index: 'Name', align: "center", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Delete', index: 'Delete', width: 25, resizable: false, align: 'center', classes: 'not-editable-cell' }
],
width: '490',
caption: 'Company Trucks',
hidegrid: false,
delete: true,
cellEdit: true,
viewrecords: true,
gridComplete: function () {
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
if (isDeleted != 'true') {
grid.jqGrid('setCell', ids[i], 'Delete', '<img src="/Images/delete.png" alt="Delete Row" />');
}
else {
grid.jqGrid('setCell', ids[i], 'Delete', ' ');
//grid.jqGrid('setCell', ids[i], 'Privileges', 'admin');
}
}
}
}
);
grid.jqGrid('navGrid', '#pagerTrucks',
{ resize: false, add: false,search:false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pagerTrucks',
{ title: "Add New Truck", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewTruckModal, position: "First", caption: "" });
});
function showNewTruckModal() {
var grid = jQuery("#TrucksGrid141");
$("#formAddNewTruck").dialog(
{
open: function (event, ui) {
$("#txtName").val('');
$("#trFormErrorTrucks").hide();
$("#trFormErrorTrucks td").text('');
},
buttons: {
"Submit": function () {
debugger;
if (ValidateUsers() == true) {
$('#error').ajaxError(function (event, request, settings) {
$('#waiting').hide();
$(this).addClass('errordiv').text(request.statusText + "" + request.status);
});
$.post('/Admin/AddNewTruck/',
$('#formAddNewTruck').serialize(),
function (data) {
debugger;
if (data == 'Success') {
$('#formAddNewTruck').dialog("close");
grid.jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
else {
$("#trFormErrorTrucks").show();
$("#trFormErrorTrucks td").text(data);
}
});
}
},
"Cancel": function () {
$('#error').removeClass("errordiv").text("");
$('#waiting').hide();
$(this).dialog("close");
}
},
modal: true,
title: "New Truck",
minWidth: 400,
resizable: false
}
).dialog('open');
}
function ValidateUsers() {
var flag = true;
var errorMSG = '';
$("#trFormErrorTrucks td").text('');
if ($("#txtName").val() == '') {
errorMSG += 'Truck Name cannot be blank';
flag = false;
}
if (flag == false) {
$("#trFormErrorTrucks").show();
$("#trFormErrorTrucks td").text(errorMSG);
}
else {
$("#trFormErrorTrucks td").text('');
$("#trFormErrorTrucks").hide();
}
return flag;
}
function deleteRow(rowid) {
jQuery("#TrucksGrid141").delGridRow(rowid, { url: '/Admin/TruckDelete', caption: 'Delete User?', msg: 'Delete selected User? <br />Careful, this is irreversable!', resize: false,success:abc });
}
function emptyText(rowid, cellname, value, iRow, iCol) {
if (cellname == 'Password')
return "";
}
function abc(data)
{
debugger;
}
and here is my cs code from controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TruckDelete(int Id)
{
var error = "";
bool result=true;
DataContext db = new DataContext();
Truck udelete= db.Trucks.Where(el => el.Id == Id).FirstOrDefault();
if (udelete != null)
{
JobSites_ForSnow snow = db.JobSites_ForSnow.Where(el => el.TruckId == Id).FirstOrDefault();
JobSite normal = db.JobSites.Where(el => el.TruckId == Id).FirstOrDefault();
if(snow==null && normal==null)
{
db.Trucks.Remove(udelete);
db.SaveChanges();
}
else
{
error = "Truck in use!";
result= false;
}
}
else
{
error = "Record Not Found!";
result= false;
}
return Json(result,error);
}
can anybody tell me how can i display the error message? i have seen this answer (jqgrid error message on delete) but didn't understood what to do :(. if the question is not clear to you, please let me know by comment, i will explain ...thanks in advance :)
You use currently
return Json(result,error);
as the last line of TruckDelete action, where result have boolean type and error is a string. So the Controller.Json Method (Object, String) where error will be interpreted as contentType of HTTP response. It's your first problem. You should use probably something like
return Json(new Object[] {result, error});
(see here). In the case the method will generate JSON response like
[true,""]
or
[false,"Record Not Found!"]
The client side (jqGrid) can process the response inside of afterSubmit callback. You need just replace unknown (for jqGrid) option success of delGridRow to the following
jQuery("#TrucksGrid141").delGridRow(rowid, {
url: '/Admin/TruckDelete',
caption: 'Delete User?',
msg: 'Delete selected User? <br />Careful, this is irreversable!',
resize: false,
afterSubmit: function (jqXHR) {
return $.parseJSON(jqXHR.responseText); // return decoded response
}
});