I'd like to refresh an MVC Dropdownlist from a JsonResult method.
Here's the public method that returns the result:
[HttpPost]
[ValidateAntiForgeryToken]
[CustomAuthorize]
public JsonResult GetHtmlApplicationSelectionList()
{
try
{
List<SelectListItem> applicationList = new List<SelectListItem>();
SelectListItem defaultApplicationValue = new SelectListItem();
defaultApplicationValue.Value = "0";
defaultApplicationValue.Text = "-- Select Application --";
defaultApplicationValue.Selected = true;
applicationList.Add(defaultApplicationValue);
foreach (var app in businessLogic.GetApplications().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Name }))
{
applicationList.Add(app);
}
return Json(new { result = "success", list = applicationList }, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json(new { result = "failure", message=ex.Message}, JsonRequestBehavior.AllowGet);
}
}
And here's the jQuery function that calls the POST method to get the updated list of applications:
function UpdateApplicationList() {
$.ajax({
url: 'Global/GetHtmlApplicationSelectionList',
type: 'POST',
dataType: 'json',
success: function (data) {
$('.applicationSelector').html('');
$('.applicationSelector').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
}
How can I force the $(.applicationSelector') dropdownlist to contain the new list without having to loop through the list retured as JSON? Is it possible to return the html of the list( applicationList) and just refresh the html using
$('.applicationSelector').html(data); ?
You need to append an <option> for each item.
This is the answer taken from this post which provides a pretty simple and straight forward example.
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
Where var selectValues is your JSON list
Related
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.
View
function editEmployee(val) {
var a = ko.toJSON(val);
// alert("Hi");
$.ajax({
url: "#Url.Action("editEmployee", "Registration")",
contentType: "application/json; charset=utf-8",
type: "POST", dataType: "json",
data:a,
success: function (data) {
// alert("awa");
debugger;
DisplayUI.getEmpArray(data);
var abc = DisplayUI.getEmpArray();
}
});
}
Controller
[HttpPost]
public JsonResult editEmployee(string ID)
{
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//dynamic item = serializer.Deserialize<object>(ID);
var employee = from s in db.Employee
select s;
try
{
if (!String.IsNullOrEmpty(ID))
{
employee = employee.Where(s => s.empId.Contains(ID));
}
}
catch (Exception ex)
{
}
var val = Json(employee.Select(s => new { s.empId, s.firstName, s.lastName, s.mobilePhn, s.email, s.desigId }).ToList());
return val;
}
Through ajax call I'm passing the value into controller as a string variable(ID). But that value is not passing it is visible as null value. I want to know get the value as a parameter what i should do.
Check whether you are getting json object
var a = ko.toJSON(val); // here you should check whether you are getting json object
Only if you get json object,the value will be bind to the controller.
put alert like this
var a = ko.toJSON(val);
alert(a);
if it is json object it will show like this
[object],[object]
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
I am quite new to MVC and Jquery and I am trying to dynamically load data from a database to populate a dropdown list. Although the data is returned from the controller, it is not displayed in the dropdown. What is wrong here?
Here is my controller code:
public JsonResult GetReasonforLeave(int typecode)
{
List<LeaveReason> reason_list = itlbg1.LeaveReasons.Where(f => f.LeaveType_typeCode == typecode).ToList();
return Json(reason_list, JsonRequestBehavior.AllowGet);
}
Here's the jquery:
function getreason(selecteditem) {
sel_val = selecteditem.value;
$.getJSON("/Leave/GetReasonforLeave", { typecode: sel_val })
.done(function (data) {
var options = $("#reason");
$.each(data, function (item) {
options.append($("<option />").val(item.reasonID).text(item.description));
});
});
}
Did the changes Stephen requested and it worked. Here's the working code FYI. Thanks Stephen.
Jquery:
function getreason(selecteditem) {
sel_val = selecteditem.value;
$.getJSON("/Leave/GetReasonforLeave", { typecode: sel_val })
.done(function (data) {
alert(data);
var options = $("#reason_dd");
options.empty();
$.each(data, function (index, item) {
options.append($("<option />").val(item.value).text(item.text));
});
});
}
Changed controller to:
public JsonResult GetReasonforLeave(int typecode)
{
var reason_list = itlbg1.LeaveReasons.Where(f => f.LeaveType_typeCode == typecode).Select(r => new { value = r.reasonID, text = r.description });
return Json(reason_list, JsonRequestBehavior.AllowGet);
}
Everything seems OK but value shows empty..
I have 2 dropdownlist, when I choose first one, I got the index and used ajax to fill other dropdownlist.. But problem is that I dont have result.. loop that is in ajax, doesnt work.. and I checked web tool of firefox, result seems empty, but in C# code, the list has items..
so here is my ajax
$.ajax({
url: "#Url.Action("ElectionList", "Home")",
type: "GET",
dataType: "json",
data: { electionTypeId: selectedId },
success: function (data) {
if (data != null) {
//HERE IS WORKING
alert("OK");
electionCombo.html('');
$.each(data, function (index,item) {
//here is not working !!!
alert("hobaaa: " + index);
alert("data: " + item.Text);
// alert(option.ID + " " + option.politicName);
// electionCombo.append($('<option></option>').val(option.Value).html(option.Text));
});
}
here is my c# code
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ElectionList(int electionTypeId)
{
var service = new EvoteServicesProviderClient();
try
{
var electtionType = service.getAllElectionTypes().FirstOrDefault(e => e.ID == electionTypeId);
var res =
service.searchElectionByType(electtionType.electionTypeName)
.ToList()
.Where(e => e.startDate >= DateTime.Now)
.Select(e => new SelectListItem
{
Value = e.ID.ToString(),
Text = e.politicName
});
var list = new SelectList(res, "Value", "Text");
return Json(list, JsonRequestBehavior.AllowGet);
// return Json(new { success = true, result = list },
// JsonRequestBehavior.AllowGet);
}
catch{}
return Json(new { success = false, message = "An error occured" }, JsonRequestBehavior.AllowGet);
}
this is the html side
#using (Html.BeginForm("ElectionList", "Home", FormMethod.Post, new {#class = "form-horizontal", id = "electionlistform"}))
{
#Html.LabelFor(m => m.SelectedElectionId, new {#class = "col-md-2 control-label"})
#Html.DropDownListFor(m => m.SelectedElectionId, Model.ElectionList, new {#class = "form-control", id = "electionList"})
#Html.ValidationMessageFor(m => m.SelectedElectionId)
}
As I wrote, the list is not empty (in actionresult ElectionList)
What I am missing?
Try this :
$.each(data, function () {
//here is not working !!!
alert("hobaaa: " + this.Value);
alert("data: " + this.Text);
});
You can access the property directly because it's json.
UPDATE
Just return the list server side :
var res =
service.searchElectionByType(electtionType.electionTypeName)
.ToList()
.Where(e => e.startDate >= DateTime.Now)
.Select(e => new SelectListItem
{
Value = e.ID.ToString(),
Text = e.politicName
});
return Json(res, JsonRequestBehavior.AllowGet);
What I do when I need to fill a dropdown is the same as you, but I'm using a for loop instead of each (maybe it's the same but for me it's working). And by the way, in your ajax code sample you are not closing the ajax function. Hope in your real code it's okay.
$.ajax({
url: "#Url.Action("ElectionList", "Home")",
type: "GET",
dataType: "json",
data: { electionTypeId: selectedId },
success: function (data) {
if (data != null) {
//HERE IS WORKING
alert("OK");
electionCombo.html('');
for (i in data) {
var result = data[i];
// electionCombo.append($('<option></option>').val(result.Value).html(result.Text));
}
}
});
By the way, if it's still not working , you could try a ViewModel with the options you need
public class ViewModelExample
{
public Int32 ValueOption { get; set; }
public String TextOption { get; set; }
}
And use it in your list instead of selectlist. With viewmodels I don't have problems getting the values with json.