How can I return custom validation messages using JsonResult and AJAX?
Here is my controller action to add a student in StudentDB.
UPDATED:
[HttpPost()]
public ActionResult AddStudent(string studentName, int studentId)
{
var studentPresent = studentTable.Students.Where(s => s.StudentID == studentId&& b.StudentName == studentName);
if (studentPresent == null || !studentPresent .Any())
{
var student = new Student()
{
StudentName = studnetName,
StudentID = studentId,
};
studentTable.AddObject("Student", student);
studentTable.SaveChanges();
}
return new JsonResult();
}
Here is my JavaScript:
function addStudent() {
$.ajax({
type: 'POST',
url: '/StudentAdmin/AddStudent',
data: {
studentName: $('#studentName').val(),
studentNumber: GetTextBoxValue('#studentNumber'),
},
success: function (result) {
if ($('#studentPresent').val() == null) {
showMessage('Success', 'Student saved successfully.', '', false);
} else {
showMessage('Error', 'Student already present in database.', '', false);
}
GetGrid('#studentGrid').ajaxRequest();
hideForm();
},
studentPresent: function (result) {
showMessage('Error', 'Student Already present in Database.', '', true);
}
});
}
I want to display the "error" message if this student is already present in database.
Also, Is there a way of passing more validation messages to JasonResult?
Thanks in advance.
You can pass any object to the JsonResult object and it will be serialized (or it will attempt to serialize) down to the javascript.
return new JsonResult(new { Anything = "Hello World" });
That results in a JSON object like so:
{"Anything":"Hello World"}
Being rendered to your javascript in the result variable.
Your code above actually doesn't show any error message being generated; you would need a try / catch block if you want to get the text of the SQL exception.
EDIT:
You would have code like so:
return Json(new { message = "Success" }); // success message
return Json(new { message = "Failure" }); // fail message
And then in javascript, your callback is like so:
success: function(result)
{
if(result.message == "Success")
// Show success message
else
// Show Error Message
}
You can return Json(new {result = "Success"});
Related
Here I EditMyProfile method which is used to edit the customer detail.
In this method I am trying to set ViewBag.msg = 1 and return return PartialView("MyProfile", getCusomerDetail);, set ViewBag.msg = 0; and return return PartialView("EditMyProfile", customer); and using that ViewBag.msg value want put condition on AJAX success whether to show success message or not.
Now, the problem is that even though the ViewBag.msg has value in EditMyProfile view, the var message = '#ViewBag.msg' gives var message = "" in AJAX success.Any help with my code will be a great help
Thank you
Below is my AJAX
<script>
$(document).ready(function () {
$("#EditMyProfileCreate").submit(function (ev) {
debugger;
ev.stopImmediatePropagation();
var Action = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: Action,
type: 'POST',
data: formData,
async: false,
success: function (data) {
debugger
var message = '#ViewBag.msg'; // Here the var message = "" even though #ViewBag.msg' has value
if (message == "1") {
swal("Congratulations!", "Chages saved successfully", "success");
$("section#myAccountMainDiv").html(data);
}
else {
$("section#myAccountMainDiv").html(data);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
})
Below is my
[HttpPost]
public ActionResult EditMyProfile(CustomerVM customer)
{
if (ModelState.IsValid)
{
using (emedicineEntities _db = new emedicineEntities())
{
var getCustomer = _db.Customers.Where(x => x.CustomerId == customer.CustomerId).FirstOrDefault();
getCustomer.CustomerName = customer.CustomerName;
getCustomer.CustomerPhoneNumber = customer.CustomerPhoneNumber;
getCustomer.CustomerEmail = customer.CustomerEmail;
getCustomer.CustomerAddress = customer.CustomerAddress;
getCustomer.ConfirmPassword = getCustomer.PasswordHash;
_db.Entry(getCustomer).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.msg = 1; // here ViewBag.msg is set 1 on successfull edit
var getId = Global.CustomerId;
var getCusomerDetail = _db.Customers.Where(x => x.CustomerId == getId).FirstOrDefault();
return PartialView("MyProfile", getCusomerDetail);
}
}
else
{
ViewBag.msg = 0; // here ViewBag.msg is set 0 when model is invalid
return PartialView("EditMyProfile", customer);
}
}
To Access ViewBag dictionary in javascript, your Javascript code block must be on the cshtml file and not in the external javascript file.
In Controlller
public ActionResult Index()
{
ViewBag.Data = "haha";
return View();
}
In cshtml file
<script>
$(document).ready(function () {
alert('#ViewBag.Data');
});
</script>
As you are calling your controller through an Ajax call, you need to return the data as a variable inside your partial view. What i would suggest is to create a hidden field inside your partial view's cshtml file and assign that the value of ViewBag property at compile time. Then inside success function get the value of hidden field and compare.
I want to be able to return json object with a custom error/success message using the same line of code on post request: i have these two lines of code:
return Json(data);
return Json(new { f = "error" });
I want to be able display it in one line like this:
return Json(data, Json(new { f = "error" }));
I know i can't have multiple return statements in my code. but i want to return the data with message.
My ServerSide Code:
if (getId > 0)
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { s = "success" });
}
else
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { f = "error" });
}
My Ajax Fucntion:
<script type = "text/javascript">
$(document).ready(function () {
$('#tblAppointment').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
});
var table = $("#tblAppointment").DataTable();
$("#saveButton").click(function () {
console.log("appDate:" + $('.datetimepicker').val());
$.ajax({
url: '/Appointment/InsertPatientAppointment/',
type: "POST",
data: JSON.stringify({
appointmentDate: $(".datetimepicker").val(),
patientRegNo: $("#patientRegNo").val(),
reasons: $("#reasons").val()
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Failed!",
text: _data.f, //"Ooops! something went wrong,
record not saved,
try again later ",
type: "info"
});
table.clear().draw();
//table.destroy();
// $("#viewReportBtn").prop("disabled", false);
return false;
} else {
swal({
title: "Success!",
text: _data.s, //"Appointment added successfully!",
type: "success"
});
}
$(".datetimepicker").val('');
$("#patientRegNo").val('');
$("#reasons").val('');
var arr = $.map(JSON.parse(_data), function (el) {
return
el
});
if (arr.length === 0) {
swal({
title: "No Record Found!",
text: _data.f, //"Your search returns an empty
result set !",
type: "info"
});
table.clear().draw();
return false;
}
table.clear();
table.destroy();
$('#tblAppointment').dataTable({
data: arr,
columns: [{
"data": "MatricRegNo"
},
{
"data": "PatientName"
},
{
"data": "EntryDate"
},
{
"data": "AppointmentDate"
},
{
"data": "Reasons"
},
{
"data": function (data, type, row, meta) {
return '<span class="fa fa-edit" data-
toggle = "modal"
data - target = "#modal-Edit" > < /span>';
}
}
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'Portriat',
pageSize: 'A4'
}
]
});
table = $("#tblAppointment").DataTable();
}
});
});
});
</script>
You can use this:
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
var returnData = new object[2];
returnData[0] = data;
returnData[1] = new { f = "error" };
return Json(returnData);
You can integrate the data object in your anonymous object which you are already returning:
return Json(new {data = data, f = "error"});
If you do it like this, you can access the data object in your ajax call like this:
success: function (_data) {
var returnedData = _data.data;
}
Which means you have to adjust your map method call where you are preparing the data array for the table. Instead of:
var arr = $.map(JSON.parse(_data), function (el) { return el });
call it with the data object _data.data:
var arr = $.map(JSON.parse(_data.data), function (el) { return el });
This should do the trick.
I would potentially approach in the following manner, extend the JsonResult to include a status code. This way you can dictate the level of success to the Ajax request.
public class JsonResultWithStatusCode : JsonResult
{
private readonly HttpStatusCode statusCode;
public JsonResultWithStatusCode(object data, HttpStatusCode statusCode)
{
Data = data;
this.statusCode = statusCode;
}
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.StatusCode = (int)statusCode;
base.ExecuteResult(context);
}
}
Then inside your controller:
if(...)
{
var model = JsonConvert.SerializeObject(...);
return new JsonResultWithStatusCode(model, HttpStatusCode.Ok)
}
else
{
var model = new { error = "..." };
return new JsonResultWithStatusCode(model, HttpStatusCode.InternalServerError);
}
Then inside your Ajax you would be able to read the status code and then read the body.
.success: function(response) {
console.log(response.status); // Status Code (200 or 500 based on above)
console.log(response.data); // Our model based on above, one writing error the other actual model data.
}
All you would have to do would be read based on the server output.
I have a JQuery function that load some data from C# and update information on my view.
I must to load a large dataset and all works fine, but for some reason i must to load a dynamic list and elaborate its from JQuery.
The list is "listCasistiche" and when i load it from MVC the JQuery function goes in error.
How can i take this list?
The JQuery function is this:
var data = $('#jqxgrid').jqxGrid('getrowdata', rowindex);
var uf = new FormData();
uf.append("id", data.Id);
var url = "/Clienti/LoadSelezionato";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
// The function go in error
},
success: function (result) {
if (result != "error") {
result.listCasistiche.forEach(function (entry) {
alert(entry.IdCasistica);
});
ricaricaNeri();
$('#OwnLead').val(result.ownerLead);
$('#dataLead').datepicker('setDate', result.dataLead);
}
}
});
The MVC LoadSelezionato function is this. All other parameters are loaded well:
[HttpPost]
public ActionResult LoadSelezionato(FormCollection form)
{
int id = Convert.ToInt32(form["id"]);
try
{
Cliente clienteLead = conc.Clientes.FirstOrDefault(x => x.Id == id);
if (clienteLead != null)
{
var elemento = new
{
ownerLead = clienteLead.OwnerLead,
dataLead = clienteLead.DataLead,
listCasistiche = conc.CasisticheClientes.Where(x => x.IdCliente == id).ToList()
};
return Json(elemento, JsonRequestBehavior.AllowGet);
}
else
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
Thanks to all
Not Returning To AJAX Success From C# Controller Action
I Have Tried Many Options Available But Its Still Not Returning Data To AJAX Success What Could Be The Reason ?
I Want To Return List Listemr_t_Immunization From Action Of Controller To My Success data Of The AJAX Call How Should I Do That
Please See The Following Code Thank You
AJAX Request
$.ajax(
{
url: '#Url.Action("getmedi", "Immunization")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ "patient2": patient2}),
success: function (data) {
debugger
$(data).each(function(index, element){
$('#first > tbody').append('<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
$('#first > tbody > tr:last-child > td:nth-child(1)').append('<input id='+element.ImmunizationId+' value='+element.VaccineName+'>');
$('#first > tbody > tr:last-child > td:nth-child(2)').append('<input id='+element.Immunization_Id+' value='+element.DateGiven+'>');
$('#first > tbody > tr:last-child > td:nth-child(3)').append('<input id='+element.Immunization_Id+' value='+element.Route+'>');
})
$("input[name='VaccineName']").attr('disabled', 'disabled');
$("input[name='DateGiven']").attr('disabled', 'disabled');
$("input[name='Route']").attr('disabled', 'disabled');
},
error: function (textStatus, errorThrown)
{
debugger
}
});
Controller Action
[HttpPost]
public JsonResult getmedi(int patient2)
{
if (patient2.ToString() != "")
{
string roster = objOrgCont.getmedi(patient2);
JavaScriptSerializer ser = new JavaScriptSerializer();
emr_t_Immunization erx = (emr_t_Immunization)ser.Deserialize(roster, typeof(emr_t_Immunization));
List<emr_t_Immunization> Listemr_t_Immunization = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList();
///List<emr_t_Medical_History> Listemr_t_Medical_History2 = (from Allemr_t_Medical_History in db.emr_t_Medical_History where Allemr_t_Medical_History.Mr_No == Mr_No select Allemr_t_Medical_History).ToList();
if (erx != null)
{
//return Json(new { success = true, for_Date = erx.Med_Date, for_Name = erx.Name, for_Active = erx.Active, for_Resolved = erx.Resolved, for_Comments=erx.Comments });
return Json(new { Listemr_t_Immunization, JsonRequestBehavior.DenyGet });
}
}
return Json(new { success = false });
}
I Have Also Tried To Stringify It Before Returning And It Shows Following Error
I Have Used
return JsonConvert.SerializeObject(Listemr_t_Immunization);
Now It Is Giving Me Error
Self referencing loop detected with type
'System.Data.Entity.DynamicProxies.as_t_appointment_305685F58BEE75BAC95975F9457412A0DE58BB59D3EDBD1155C7DB5E21A7BA66'.
Path
'[0].erx_t_patient.as_t_appointment[0].erx_t_city.as_t_appointment'
Just from a quick glance, it looks like you could move your failure returns into else statements to protect them from being fired unless one of your conditions fail, rather than just floating outside on its own.
Is the issue that your call back fails every time? If so that could be the reason.
[HttpPost]
public JsonResult getmedi(int patient2)
{
if (patient2.ToString() != "")
{
string roster = objOrgCont.getmedi(patient2);
JavaScriptSerializer ser = new JavaScriptSerializer();
emr_t_Immunization erx = (emr_t_Immunization)ser.Deserialize(roster, typeof(emr_t_Immunization));
List<emr_t_Immunization> Listemr_t_Immunization = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList();
///List<emr_t_Medical_History> Listemr_t_Medical_History2 = (from Allemr_t_Medical_History in db.emr_t_Medical_History where Allemr_t_Medical_History.Mr_No == Mr_No select Allemr_t_Medical_History).ToList();
if (erx != null)
{
//return Json(new { success = true, for_Date = erx.Med_Date, for_Name = erx.Name, for_Active = erx.Active, for_Resolved = erx.Resolved, for_Comments=erx.Comments });
return Json(new { Listemr_t_Immunization, JsonRequestBehavior.DenyGet });
} else
{
return Json(new { success = false });
}
} else
{
return Json(new { success = false });
}
}
Also on a side note, a better way to deal with success and failure of API-ish stuff is to use the HTTP error codes.
Response.StatusCode = (int)HttpStatusCode.Created;
return Json(new { results });
EDIT
To send a list back in your request.
This line here will need to change:
List<emr_t_Immunization> Listemr_t_Immunization = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList();
I am guessing that db is your context object and if so replace that line with:
var results = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList()
I am not 100% sure what erx is, but if you are checking that you have results then change that to.
if (results.Any())
{
Response.StatusCode = (int) HttpStatusCode.Created;
return Json(new { results });
} else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Failed");
}
So all up your code will read:
[HttpPost]
public JsonResult getmedi(int patient2)
{
if (patient2.ToString() != "")
{
string roster = objOrgCont.getmedi(patient2);
JavaScriptSerializer ser = new JavaScriptSerializer();
emr_t_Immunization erx =(emr_t_Immunization)ser.Deserialize(roster, typeof(emr_t_Immunization));
var results = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList()
/// You can make that query easier to read by having
/// var results = db.emr_t_Immunization.Where(a => a.Patient_Id == patient2).ToList()
if (results.Any())
{
Response.StatusCode = (int) HttpStatusCode.Created;
return Json(new { results });
} else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Failed");
}
} else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Failed");
}
}
I have created a following model
public class myModel
{
public int ID;
public string Name;
public int[] days;
}
Then I created an action in a controller
[HttpPost]
public ActionResult myCtrlAction(myModel thisModel)
{
if (ModelState.IsValid)
{
return Json(thisModel);
}
else
{
string errorMessage = "<div class=\"validation-summary-errors\">"
+ "The following errors occurred:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li class=\"field-validation-error\">"
+ error.ErrorMessage + "</li>";
}
}
errorMessage += "</ul>";
return Json(new myModel { Name = errorMessage }); //just for now
}
}
In my javascript I send the data using jQuery.post() as
$("#myBtn").click(function () {
var mydata = {
ID: $("#inputID").val(),
Name: $("#inputName").val(),
Days: $("#selectDays").select2("val")
}
var url = 'myController/myCtrlAction'; //definitly it was writtern as #Url.Action
$.post(url, mydata, function(data) { alert(data); //which shows [object object]
}, 'json');
});
Now On request when I debug in Chrome I saw in headers as
Form Data
ID: 5
Name: SomeName
Days[]: 6
Days[]: 5
In Response I got json format of my model as
{ID: "0", Name: "null", Days: "null"} it means my model state is valid but why its not having the values?
Any body has any idea. what I did wrong or do I miss something?
I think your model's data is not set thus you get null values on Chrome.
If your javascript does not have a typo (and that you only made a typo when creating the question, then try this in your method myCtrlAction;
First try create getters and setters for your fields in myModel. Then;
replace;
errorMessage += "</ul>";
return Json(new myModel { Name = errorMessage }); //just for now
with this;
myModel myMODTest= new myModel();
myMODTest.setID(1111);
myMODTest.setName("testName");
myMODTest.setDays({1,2,3});
return Json(myMODTest); //just for now
See if you get on your browser the following;
{ID: "1111", Name: "testName", Days: "{1,2,3}"}
I do this following:
1: JavaScript: When clicking the button: Serialize the form-data and send it to the Controller:
function ajaxSubmitEditSupplierQuote() {
var formData = $("#SupplierQuoteEditForm").serializeArray();
$.ajax({
type: "POST",
url: '#Url.Action("Edit", "SupplierQuote")',
data: formData,
dataType: "json",
cache: false,
success: function (data1) {
// Here I create then a new Url-string.
// Simple access your Json Data, as you have named it in the return of the Controller-Action.
var strUrl = "/Equipment/" + data1.target.toString();
// ...
//
// ...
}
});
}
2: Controller-Action with custom Json return
[HttpPost]
public ActionResult Edit(SupplierQuoteDto supplierQuoteDto)
{
// ........... code
if (_userContext.EquipmentAction.ClickedAction == ActionType.Create)
return Json(new { target = "Create" });
else if (_userContext.EquipmentAction.ClickedAction == ActionType.Edit)
return Json(new { target = "Edit" });
else
return new EmptyResult();
}
3: Alternatively if you want to catch also the EmptyResult() then in the JavaScript, check simply in the
success: function (data1) {
if (data1.toString() == "") {
// .... alert
}
else {
/// .... go on with coding
}
}
check your javascript code where you do the post. You have a typo: '.' instead of ',':
$.post(url, mydata, function(data) { alert(data); }, 'json');