In my app I need to loop through my Knockout observable array of objects with observable properties. This is so I can post each object back to the server.
I can access my model but I can not access the child elements, which I would like to post back to the server.
My client code is
self.postAllReqs = function(self) {
self.error(''); // Clear error message
var model = ko.toJSON(self.Reqs); // convert to json
for (var item in model) {
ajaxHelper(reqsUri, 'POST', item).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
})
}
}
How do I access the child element please?
Extract of my View Model
function ReqsTest(rt) {
rt = rt || {};
var self = this;
self.id = ko.observable(rt.ID || 0);
self.requisition = ko.observable(rt.Requisition || "");
self.reqnStatus = ko.observable(rt.ReqnStatus || "");
self.dateReqnRaised = ko.observable(rt.DateReqnRaised|| null);
self.reqnValue = ko.observable(rt.ReqnValue || null);
self.approvedValue = ko.observable(rt.ApprovedValue || null);
self.originator = ko.observable(rt.Originator || "");
self.origName = ko.observable(rt.OrigName || "");
self.origEmail = ko.observable(rt.OrigEmail || "");
self.line = ko.observable(rt.Line || 0.00);
self.indx = ko.observable(rt.INDX || 0);
self.dateReqnRaisedL = ko.observable(rt.DateReqnRaisedL || null);
self.reqStatus = ko.observable(rt.ReqStatus || "");
//self.reqBackground = ko.observable(rt.ReqBackground || "");
//Computed observables
self.reqBackground = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "card-heading bg-success text-white"; }
else if (status == "D") { return "card heading bg-secondary"; }
else if (status == "R") { return "card heading bg-warning"; }
else if (status == "E") { return "card heading bg-danger"; }
else {
return "card-heading bg-primary text-white";
}
})
self.reqStatusLabel = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "Approved"; }
else if (status == "D") { return "Declined - put on hold"; }
else if (status == "R") { return "Routing On"; }
else if (status == "E") { return "Erase On Syspro"; }
else {
return "Awaiting Approval";
}
})
self.approvalBtn = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "css: button btn-secondary "; }
else {
return "btn btn-success ";
}
})
self.approvalBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "W") { return "Approve"; }
else {
return "UnApprove";
}
})
self.declineBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "D") { return "UnDecline"; }
else {
return "Decline";
}
})
self.deleteBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "E") { return "Restore"; }
else {
return "Erase";
}
})
// Functions
//show details alert
$(".btn").on("click", function () {
$(".alert").removeClass("in").show();
$(".alert").delay(200).addClass("in").fadeOut(2000);
});
}
function ReqsViewModel (){
var self = this;
self.Reqs = ko.observableArray([]);
self.error = ko.observable();
var reqsUri = '/api/ReqsTests/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllReqs() {
ajaxHelper(reqsUri, 'GET').done(function (data) {
// Build the ReqsTest objects
var reqs = ko.utils.arrayMap(data, function (rt) {
return new ReqsTest(rt);
});
self.Reqs(reqs);
});
}
From what I can tell with the code provided, there is nothing calling the getAllReqs as its a private function withing the ReqsViewModel.
I'm not exactly clear on what your issue is, so I have created a quick demo using your example code to show how you can interact with items in the array.
var app = {};
function ReqsTest(rt, saveItemFn) {
rt = rt || {};
var self = this;
self.id = ko.observable(rt.ID || 0);
self.requisition = ko.observable(rt.Requisition || "");
self.reqnStatus = ko.observable(rt.ReqnStatus || "");
self.dateReqnRaised = ko.observable(rt.DateReqnRaised || null);
self.reqnValue = ko.observable(rt.ReqnValue || null);
self.approvedValue = ko.observable(rt.ApprovedValue || null);
self.originator = ko.observable(rt.Originator || "");
self.origName = ko.observable(rt.OrigName || "");
self.origEmail = ko.observable(rt.OrigEmail || "");
self.line = ko.observable(rt.Line || 0.00);
self.indx = ko.observable(rt.INDX || 0);
self.dateReqnRaisedL = ko.observable(rt.DateReqnRaisedL || null);
self.reqStatus = ko.observable(rt.ReqStatus || "");
//self.reqBackground = ko.observable(rt.ReqBackground || "");
//Computed observables
self.reqBackground = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "A") {
return "card-heading bg-success text-white";
} else if (status == "D") {
return "card heading bg-secondary";
} else if (status == "R") {
return "card heading bg-warning";
} else if (status == "E") {
return "card heading bg-danger";
} else {
return "card-heading bg-primary text-white";
}
})
self.reqStatusLabel = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "A") {
return "Approved";
} else if (status == "D") {
return "Declined - put on hold";
} else if (status == "R") {
return "Routing On";
} else if (status == "E") {
return "Erase On Syspro";
} else {
return "Awaiting Approval";
}
})
self.approvalBtn = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "A") {
return "css: button btn-secondary ";
} else {
return "btn btn-success ";
}
})
self.approvalBtnLbl = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "W") {
return "Approve";
} else {
return "UnApprove";
}
})
self.approve = function() {
if (self.reqStatus() == 'W') {
self.reqStatus("A");
} else {
self.reqStatus("W");
}
saveItemFn(self);
}
self.declineBtnLbl = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "D") {
return "UnDecline";
} else {
return "Decline";
}
})
self.deleteBtnLbl = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "E") {
return "Restore";
} else {
return "Erase";
}
})
// Functions
//show details alert
$(".btn").on("click", function() {
$(".alert").removeClass("in").show();
$(".alert").delay(200).addClass("in").fadeOut(2000);
});
}
function dataService(serviceUrl) {
var url = serviceUrl;
function getData() {
// do ajax call here
return {
done: function(fn) {
return fn(app.externalData);
}
}
}
function saveItem(item) {
// add posting to server here.
alert("Saving item: " + item.id());
}
return {
getData: getData,
saveItem: saveItem,
};
}
function ReqsViewModel(dataService) {
var reqsUri = 'api/ReqsTests/';
var self = this;
self.Reqs = ko.observableArray([]);
self.error = ko.observable();
self.getAllReqs = getAllReqs;
function getAllReqs() {
dataService.getData().done(function(data) {
// Build the ReqsTest objects
var reqs = ko.utils.arrayMap(data, function(rt) {
return new ReqsTest(rt, dataService.saveItem);
});
self.Reqs(reqs);
});
}
}
app.dataService = dataService;
app.externalData = [{
ID: 1,
Requisition: "Requisition 1",
ReqnStatus: "A",
DateReqnRaised: "2019-01-01T11:00:00+11:00",
ReqnValue: 200.24,
ApprovedValue: 200,
Originator: "Slartibartfast",
OrigName: "Requisition 1",
OrigEmail: "test#test.com",
Line: 1.1,
INDX: 1,
DateReqnRaisedL: "2019-01-01T11:00:00+11:00",
ReqStatus: "A"
}, {
ID: 2,
Requisition: "Requisition 2",
ReqnStatus: "W",
DateReqnRaised: "2019-01-02T11:00:00+11:00",
ReqnValue: 300.24,
ApprovedValue: 300,
Originator: "Slartibartfast",
OrigName: "Requisition 2",
OrigEmail: "test#test.com",
Line: 2.2,
INDX: 2,
DateReqnRaisedL: "2019-01-02T11:00:00+11:00",
ReqStatus: "W"
}];
var vm = new ReqsViewModel(app.dataService("/api/reqs/"));
vm.getAllReqs();
ko.applyBindings(vm);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Requistion</th>
<th>Raised</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: Reqs">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: requisition"></td>
<td data-bind="text: dateReqnRaised"></td>
<td><button class="btn btn-primary" data-bind="css: approvalBtn, text: approvalBtnLbl, click: approve">Approve</button></td>
</tr>
</tbody>
</table>
Related
The question is the same as this one. I want to get an object from a IActionResult with the related html status but Swagger show me a "OK" message instead of the related status.
I searched many hours to find an error in the configurations and I didn't find anything to solve the problem. I'll show you the code:
Here is the IActionResult:
[HttpPut("updateuserpricingplan")]
[ProducesResponseType(200)]
[ProducesResponseType(400, Type = typeof(ServiceValidationResult))]
public async Task<IActionResult> UpdateSelection([FromBody]UpdatePricingPlanModel model)
{
var user = await _userService.GetSignedIdUser(this.HttpContext);
var result = await _userService.UpdateUserPricingPlan(user, model.PricingPlanId, _settingService, model.Code);
if (result.Succeeded)
return Ok();
return new ObjectResult(result) { StatusCode = 400 };
}
This is interresting to know I can see the result and the status code
from the Network/Response tab in Google Chrome.
Here is how I wrote the subscribe
this.pricingPlanService.updateSelection(model)
.subscribe(res => {
console.log(res.result);
}, err => { // <== I got "OK" result as string and nothing else
console.log(err.status);
console.log(err.response);
}, () => {
this.sessionService.updatePricingPlan(selectedPricingPlan.id);
});
Now here the versions I use:
NSwagStudio: 12.1.0.0
Angular: 7.0.4
ASP.net Core 2.2.4
If it could help, here the code that is generated by NSwagStudio for updateSelection. Please note that if (response_ instanceof HttpResponseBase) seams to be always false.
updateSelection(model: UpdatePricingPlanModel): Observable<SwaggerResponse<void>> {
let url_ = this.baseUrl + "/api/PricingPlan/updateuserpricingplan";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(model);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
})
};
return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processUpdateSelection(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processUpdateSelection(<any>response_);
} catch (e) {
return <Observable<SwaggerResponse<void>>><any>_observableThrow(e);
}
} else
return <Observable<SwaggerResponse<void>>><any>_observableThrow(response_);
}));
}
protected processUpdateSelection(response: HttpResponseBase): Observable<SwaggerResponse<void>> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return _observableOf<SwaggerResponse<void>>(new SwaggerResponse(status, _headers, <any>null));
}));
} else if (status === 400) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result400: any = null;
let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result400 = resultData400 ? ServiceValidationResult.fromJS(resultData400) : <any>null;
return throwException("A server error occurred.", status, _responseText, _headers, result400);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<SwaggerResponse<void>>(new SwaggerResponse(status, _headers, <any>null));
}
Do you see any mistake or misconfiguration?
Thank you for any help,
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");
}
}
When i click on button it will call JavaScript method after that on Ajax call if i debug it on Firefox browser than it calls server side method setMandate() but not directly on button click, i don't know what is happening?
<div>
<button id="GetMandateBtn" onclick="SetMandate()" disabled>Get Mandate</button>
</div>
function SetMandate() {
var clients = new Array();
var queryNo = 0;
$("#DivMandateClients input:checked").each(function () {
clients.push($(this).attr('value'));
});
if (clients == "")
clients.push(0);
var contacts = new Array();
$("#DivMandateClientsContact input:checked").each(function () {
contacts.push($(this).attr('value'));
var value = $(this).val();
});
if (contacts == "")
contacts.push(0);
var candidateStatus = new Array();
$("#candidateStatus input:checked").each(function () {
candidateStatus.push($(this).attr('value'));
});
if (candidateStatus == "") {
candidateStatus.push(0);
queryNo = 0;
}
var mandateRegion = new Array();
$("#MandateRegion input:checked").each(function () {
mandateRegion.push($(this).attr('value'));
});
if (mandateRegion == "") {
mandateRegion.push(0);
queryNo = 0;
}
var mandateCountry = new Array();
$("#MandateCountry input:checked").each(function () {
mandateCountry.push($(this).attr('value'));
});
if (mandateCountry == "") {
mandateCountry.push(0);
queryNo = 0;
}
var researchers = new Array();
$("#Researcher input:checked").each(function () {
researchers.push($(this).attr('value'));
});
if (researchers == "") {
researchers.push(0);
queryNo = 0;
}
if (StartDateTxt.value.trim() != "" && EndDateTxt.value.trim() != "") {
$.ajax({
url: "/WebService/GetMandate",
data: "{ 'startDate' : '" + StartDateTxt.value + "','endDate' : '" + EndDateTxt.value + "','clients' : '" + clients + "','contacts' : '" + contacts + "','candidateStatus' : '" + candidateStatus + "','mandateRegion' : '" + mandateRegion + "','mandateCountry' : '" + mandateCountry + "','researchers' : '" + researchers + "','queryNo' : '" + queryNo + "'}",
dataType: "json",
type: "POST",
dataFilter: function (data) { return data; },
success: function (data) {
var mandate = $("#Mandate");
mandate.html("");
if (data != null) {
if (data != "")
mandate.append($("<input type='checkbox' id='chklstMandate-2' name='Mandate' value='-2'/> <label style='display:inline;' id='lblMandate-2'>Select All</label><hr/>"));
$.each(data, function (index, value) {
mandate.append($("<input type='checkbox' id='chklstMandate" + data[index].ResearcherId + "' name='Mandate' value='" + data[index].ResearcherId + "'/> <label style='display:inline;' id='lblMandate" + data[index].ResearcherId + "'>" + data[index].MandaName + "</label><br />"));
});
$("#chklstMandate-2").click(function (event) {
if ($("#chklstMandate-2").is(":checked"))
$("#Mandate").each(function () {
$("input[type=checkbox][name='Mandate']").attr("checked", true);
});
else if ($("#chklstMandate-2").not(":checked"))
$("#Mandate").each(function () {
$("input[type=checkbox][name='Mandate']").attr("checked", false);
});
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error on Loading Mandate" + errorThrown);
}
});
}
};
public ActionResult GetMandate()
{
// InputStream contains the JSON object you've sent
String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
// Deserialize it to a dictionary
var dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String, string>>(jsonString);
var startDate = Convert.ToDateTime(dic["startDate"]);//DateTime.Parse(dic["startDate"]);
var endDate = DateTime.Parse(dic["endDate"]);
string[] clients = dic["clients"].Split(',');
string[] contacts = dic["contacts"].Split(',');
string[] candidateStatus = dic["candidateStatus"].Split(',');
string[] mandateRegion = dic["mandateRegion"].Split(',');
string[] mandateCountry = dic["mandateCountry"].Split(',');
string[] researchers = dic["researchers"].Split(',');
int queryNo = int.Parse(dic["queryNo"]);
//bool isClientIdSelected = true;
List<int> clientIds = new List<int>();
foreach (var clnt in clients)
{
if (clnt != "-2" && clnt != "0")
clientIds.Add(int.Parse(clnt));
}
List<int> contactIds = new List<int>();
foreach (var conts in contacts)
{
if (conts != "-2" && conts != "0")
contactIds.Add(int.Parse(conts));
}
List<int> candidateStatusIds = new List<int>();
foreach (var status in candidateStatus)
{
if (status != "-2" && status != "0")
candidateStatusIds.Add(int.Parse(status));
}
List<int> mandateRegionIds = new List<int>();
foreach (var region in mandateRegion)
{
if (region != "-2" && region != "0")
mandateRegionIds.Add(int.Parse(region));
}
List<int> mandateCountryIds = new List<int>();
foreach (var country in mandateCountry)
{
if (country != "-2" && country != "0")
mandateCountryIds.Add(int.Parse(country));
}
List<int> researcherIds = new List<int>();
foreach (var researcher in researchers)
{
if (researcher != "-2" && researcher != "0")
researcherIds.Add(int.Parse(researcher));
}
if (queryNo == 0)
{
var mandaetFromDB = (from mc in dbContext.MandateCandidates
join m in dbContext.Mandates on mc.MandateId equals m.MandateId
join mr in dbContext.MandateResearchers on mc.MandateId equals mr.MandateId
where m.StartDate >= startDate
&& m.EndDate <= endDate
&& clientIds.Contains(m.ClientId)
&& contactIds.Contains(m.ContactId)
&& candidateStatusIds.Contains(mc.CandidateStatusId ?? 0)
select new { MandateId = m.MandateId, MandaName = m.Name, ResearcherId = mr.ResearcherId, ClientId = m.ClientId }).ToList();
return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
else
{
var mandaetFromDB = (from mc in dbContext.MandateCandidates
join m in dbContext.Mandates on mc.MandateId equals m.MandateId
join mr in dbContext.MandateResearchers on mc.MandateId equals mr.MandateId
where m.StartDate >= startDate
&& m.EndDate <= endDate
&& clientIds.Contains(m.ClientId)
&& contactIds.Contains(m.ContactId)
&& candidateStatusIds.Contains(mc.CandidateStatusId ?? 0)
&& mandateRegionIds.Contains(m.RegionId ?? 0)
&& mandateCountryIds.Contains(m.MandateCountryId ?? 0)
&& researcherIds.Contains(mr.ResearcherId ?? 0)
select new { MandateId = m.MandateId, MandaName = m.Name, ResearcherId = mr.ResearcherId, ClientId = m.ClientId }).ToList();
return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
//return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
I am using http://jqueryui.com/autocomplete/#combobox for my dropdownlist and it works well.
My problem here is when I disable the dropdown list from code behind it doesn't work.
My code is here.
ASPX
<asp:DropDownList runat="server" CssClass="Dropdown" ID="ddlStatus"> </asp:DropDownList>
JS
function pageLoad() {
/******** Auto Complete *********************/
$(function () {
$("#<%= ddlStatus.ClientID %>").combobox();
});
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
}
C#
Based some validations I am calling this,
ddlStatus.Enabled = false;
There is an answer here and I am not be to get it work with my code.
Disable jQuery ComboBox when underlying DropDownList is disabled
This is how I have done it. please see the changes enclosed in * *.
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
*select = this.element.hide();*
this._createAutocomplete(*select*);
this._createShowAllButton(*select*);
},
_createAutocomplete: function (*select*) {
var selected = this.element.children(":selected"),
select = this.element.hide(),
value = selected.val() ? selected.text() : "";
*var disabled = select.is(':disabled');*
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.*attr('disabled', disabled)*
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function (*select*) {
var input = this.input,
wasOpen = false;
*var disabled = select.is(':disabled');*
console.log(this.element.attr("id") + " : " + disabled);
$("<a>")
.attr("tabIndex", -1)
*.attr('disabled', disabled)*
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
*if ($(this).attr('disabled')) {
return false;
}*
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
Okay, so, my issue today is I am trying to return a jquery datatable from a AJAX result, and every time I request the AJAX I am getting the following error:
"DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error"
Here is what my view looks like:
<script type="text/javascript">
$(document).ready(function () {
var oTable = $('#StudentTable').dataTable({
"bServerSide": true,
"sAjaxSource": "Admin/FindStudent",
"bProcessing": true,
"aoColumns": [
{ "sName": "StudentID",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return 'View';
}
},
{ "sName": "FirstName" },
{ "sName": "LastName" },
{ "sName": "EmailAddress" }
]
});
});
</script>
<table id="StudentTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And here is the controller:
public ActionResult FindStudent(DataTableParamModel dtParams)
{
//if (Session["IsAdmin"] != "True")
//{
// return View("Login");
//}
var repo = new StudentRepository();
var allStudents = repo.GetAllStudents();
IEnumerable<StudentInfo> filteredStudents;
//Check whether the students should be filtered by keyword
if (!string.IsNullOrEmpty(dtParams.sSearch))
{
//Used if particulare columns are filtered
var fnameFilter = Convert.ToString(Request["sSearch_1"]);
var lnameFilter = Convert.ToString(Request["sSearch_2"]);
var emailFilter = Convert.ToString(Request["sSearch_3"]);
//Optionally check whether the columns are searchable at all
var isFNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
var isLNameSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
var isEmailSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
filteredStudents = repo.GetAllStudents()
.Where(c => isFNameSearchable && c.FirstName.ToLower().Contains(dtParams.sSearch.ToLower())
||
isLNameSearchable && c.LastName.ToLower().Contains(dtParams.sSearch.ToLower())
||
isEmailSearchable && c.EmailAddress.ToLower().Contains(dtParams.sSearch.ToLower()));
}
else
{
filteredStudents = allStudents;
}
var isFNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
var isLNameSortable = Convert.ToBoolean(Request["bSortable_2"]);
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<StudentInfo, string> orderingFunction = (c => sortColumnIndex == 1 && isFNameSortable ? c.FirstName :
sortColumnIndex == 2 && isLNameSortable ? c.LastName :
"");
var sortDirection = Request["sSortDir_0"]; // asc or desc
if (sortDirection == "asc")
filteredStudents = filteredStudents.OrderBy(orderingFunction);
else
filteredStudents = filteredStudents.OrderByDescending(orderingFunction);
var displayedStudents = filteredStudents.Skip(dtParams.iDisplayStart).Take(dtParams.iDisplayLength);
var result = from c in displayedStudents select new[] { Convert.ToString(c.StudentID), c.FirstName, c.LastName, c.EmailAddress };
JsonResult results = Json(new
{
sEcho = dtParams.sEcho,
iTotalRecords = allStudents.Count(),
iTotalDisplayRecords = filteredStudents.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
return View(results);
}
When using JSONLint, it spits out
Parse error on line 1:
<headid="Head1"><sty
^
Expecting '{', '['
Any ideas?
try to return Json object:
return Json(new {
sEcho = dtParams.sEcho,
iTotalRecords = allStudents.Count(),
iTotalDisplayRecords = filteredStudents.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
resource