$('[data-toggle="mftapproveCheck"]').click(function () {
var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get();
//alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") + "\"");
var url = $(this).data("url") + "/" + selected;
var title = $(this).data("title");
callback: function (result) {
if (result) {
$("#preLoader").fadeIn('fast');
$.post(url, function (json) {
if (json.IsComplete) {
$("#" + id).remove();
BSToastr.show("success", "Başarılı", "İşleminiz Başarıyla Gerçekleştirildi.");
}
else {
BSToastr.show("error", "Hata", "İşleminiz Gerçekleştirilemedi.");
}
$("#preLoader").fadeOut('fast');
});
}
}
});
});
Here I am trying to send selected to controller. this works when only 1 Id comes but doesnt work when several comes. but alert always working. How can I send Array from here ?
public ActionResult ApproveSelected(int[] selected)
{
var itema = selected;
var itemb = itema;
try
{
var AllParticipants = Db.Participants
.Where(m => selected.Contains(m.Id))
.OrderBy(m => m.Id)
.ToList();
for (int i = 0; i < AllParticipants.Count; i++)
{
var item = AllParticipants.First();
item.Approval = true;
var itemRemove = AllParticipants.First();
AllParticipants.Remove(item);
}
Db.SaveChanges();
}
catch
{
return Json(new { IsComplete = false });
}
return Json(new { IsComplete = true });
}
You're not sending a list because of this line:
var url = $(this).data("url") + "/" + selected;
which just concats selected without actually converting it. If you take a look at your alert, you actually convert it to a string via the join function which is why you see all the items.
selected.join(";"); // <-- used in your alert()
So what I'd suggest is using that same join call when setting your url variable:
var url = $(this).data("url") + "/" + selected.join(";");
Related
I have a Dynamic Grid in the ASP.NET page. When I click Add User, it creates an empty record with Textbox controls and when the user types something in the first Textbox - UserName, it should pull the UserNames from the Database and autocomplete should work for that Textbox control.
I have implemented jQuery.autocomplete function as below.
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
var rows = data.split("|");
var jsStr = "var datalist=[";
for (i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace("'", "\\'");
s = s.replace('"', "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",name:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (datalist) != 'undefined') {
response(jQuery.map(datalist, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
When I try to Debug this autocomplete, the data is coming at the end of response(jQuery.map(datalist, function (items) statement. But the select: option is not firing.
EDIT
The below screenshot shows how the data is formed.
And this is what is present in the Server-Side Users.aspx.vb Page_Load Event
Response.Clear()
Response.Write(GetUserName(Request.QueryString("UserName")))
Response.End()
What could be the problem?
First. In the response, you check the data variable in swith. And you get it as a string.
Second. the best way to work with ajax is JSON.
jQuery.ajax({
url: url,
dataType: 'json'
On successful response:
Make parsing.
json = JSON.parse(data)
And then you already apply your logic, I work with individual object variables.
swith(json.string){ .... }
And it will be easier to fill Textbox controls with the necessary parameters: json.user - the variable will contain an array of data about users.
Update code:
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
dataType: 'json',
/*
* format respone data (string!!!) -> {"result": [{"id": 1,"item": 2},{"id": 1,"item": 2}],"found": "VALUESFOUND"}
*/
success: function (data) {
let json = JSON.parse(data);
switch (json.found) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
response(jQuery.map(json.result, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
I have the following code which reads information from a sharepoint list and renders fine in google chrome, but when tested in IE 11 (Corporate Browser), then I get the following exception:
ReferenceError: 'Promise' is undefined
at getContentTypeOfCurrentItem (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:209:5)
at addContentType (https://ourserver.com/sites/billing/Style.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:201:5)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:163:7)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:130:399)
at m.prototype.$eval (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:145:96)
at m.prototype.$digest (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:142:165)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx
(function () {
angular
.module('BillCycleApp')
.controller('relatedBillingDocumentsController', ['$scope', '$log', '$q', 'spService', 'BillingDocuments', 'General',
function ($scope, $log, $q, spService, config, generalConfig) {
var vm = this;
var tableSelector = "#related-billing-documents-table";
var componentSelector = ".related-billing-documents";
function GetContext() {
vm.Name = config.Name;
var dataTableColumns = spService.TransformFieldsToDataTableColumns(config.FieldsToShow);
$.fn.dataTable.moment( generalConfig.DateTimeFormat );
// Initialize with empty data
$(tableSelector).DataTable({
data : [],
columns : dataTableColumns,
order : config.SortOrder,
deferRender : true
}).on( 'draw.dt', function ( e, settings, processing ) {
// Make sure the UserPresence is added every time the DataTable's data changes (paging, sorting, search,..)
spService.UserPresenceComponent.AddPresence();
});
// Make component visible
$(componentSelector).css("visibility", "visible");
// SP.js function
// Get Bill Cycle list & id
var listItemId = GetUrlKeyValue('ID', true, window.location.search, true);
var listId = "{" + GetUrlKeyValue('List', true, window.location.search, true) + "}";
var propertiesToLoad = ["FileRef","PwC_ClientCode","PwC_JobCodesMulti","PwC_EngagementCode"];
spService.GetListItem(listId, listItemId, propertiesToLoad)
.then(function(billCycle) {
var listItemValues = [];
propertiesToLoad
.forEach(function(propertyName) {
var value = billCycle.get_item(propertyName);
listItemValues[propertyName] = value;
});
var billCyclePath = _spPageContextInfo.siteAbsoluteUrl;
billCyclePath += listItemValues["FileRef"];
var clientCode = listItemValues["PwC_ClientCode"]
var jobCodesLookups = listItemValues["PwC_JobCodesMulti"];
var engagementCode = listItemValues["PwC_EngagementCode"]
var jobCodes = [];
if(jobCodesLookups) {
jobCodesLookups.forEach(function(lookup) {
jobCodes.push(lookup.get_lookupValue());
});
}
// Get data with parameters
GetData(billCyclePath, clientCode, jobCodes, engagementCode);
});
}
function GetData(billCyclePath, clientCode, jobCodes, engagementCode) {
var enhanceFunctions = [
function(searchResultRow) {
return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
},
function(searchResultRow) {
return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
},
function(searchResultRow) {
return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
},
function(searchResultRow) {
return spService.AddImageMapping(searchResultRow, config.ImageFields);
},
function(searchResultRow) {
return spService.FormatNumberFields(searchResultRow, config.NumberFields);
},
function(searchResultRow) {
// Put link to parent Bill Cycle with name = folder name
//var parentLink = searchResultRow["FileRef"];
//arrayofstrings = parentLink.split("/");
//var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
//arrayofstrings.pop();
//var hyperLink = '' + billCycleFolderName + '';
//searchResultRow["Bill Cycle"] = hyperLink;
}
];
// Get data from SP
var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); // copy array
var selectPropertiesToShow = spService.TransformFieldsToSelectProperties(config.FieldsToShow); // copy array
var extendedSelectProperties = selectProperties.slice();
var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
GetRelatedBillingDocumentsFromList(extendedSelectProperties, billCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions)
.then(function (data) {
var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectPropertiesToShow);
// Add data to dataTable
var dataTable = $(tableSelector).DataTable();
dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes
vm.ValidDataLoaded = true;
})
.catch (function (message) {
vm.Name = "Error";
vm.ValidDataLoaded = true;
});
}
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="PwC_ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(function(listItems) {
var listItemsWithValues = [];
if(listItems) {
var enumerator = listItems.getEnumerator();
var promises = [];
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function(propertyName) {
var value = listItem.get_item(propertyName);
if(propertyName === "PwC_JobCodesMulti"){
jobvalue = "";
value.forEach(function(jobvalues){
jobvalue+= jobvalues.get_lookupValue() +";";
})
listItemValues[propertyName] = jobvalue;
}else{
listItemValues[propertyName] = value;
}
});
listItemsWithValues.push(listItemValues);
}
var promises = listItemsWithValues.map(addContentType);
Promise.all(promises).then(youCanUseTheData);
function youCanUseTheData(){
/*
At this point, each listItem holds the 'Document Type' info
*/
listItemsWithValues.forEach(function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
var parentLink = listItem["FileRef"];
arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
});
var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
deferred.resolve(listItemsWithValues);
}
}
})
.catch (function (message) {
deferred.reject();
});
return deferred.promise;
}
function addContentType(listItem){
//return getContentTypeOfCurrentItem(listItem.ID.toString());
return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname) {
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
}).catch(function(error) {
$log.warn("Server error");
});
}
function getContentTypeOfCurrentItem(id) {
return new Promise(function (resolve, reject) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
var listItem2 = oList.getItemById(id);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.load(listItem2, 'ContentTypeId');
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem2.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
return resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
return reject(errorInfo);
}
);
});
}
function GetRelatedBillingDocuments(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with path [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
// TODO: AND or OR?
var jobCodesFilter = spService.ExpandSearchFilterForEachValue("JobCodes", ":", jobCodes, false, false);
var engagementCodeFilter = "";
if (engagementCode != undefined && engagementCode != "") {
engagementCodeFilter = "EngagementCode:" + engagementCode;
}
if(jobCodesFilter && engagementCodeFilter) {
jobCodesFilter += " OR ";
}
// TODO: Add use of result source?
var queryText = "-Path:" + spService.AddQuotes(currentBillCyclePath) + ' AND -ContentType:"Bill Cycle" AND ClientCode:' + clientCode + " AND (" + jobCodesFilter + engagementCodeFilter + ")";
var searchQuery = new spService.SpSearchQuery(webUrl, queryText, selectProperties, config.ResultSourceName, config.ResultSourceLevel);
searchQuery
.ExecuteSearchQueryFetchAll() // returns deferred
.then(function (results) {
$log.info("Successfully retrieved search results");
var searchResults = spService.SpSearchQuery.EnhanceSearchResults(results, enhanceFunctions);
deferred.resolve(searchResults);
});
return deferred.promise;
}
ExecuteOrDelayUntilScriptLoaded(GetContext, 'sp.js');
}
]); // End Controller()
}()); // End IFFE
Promise is part of ES6 standard that is not fully supported by IE11, you can use babel-polyfill instead or use another librairy like q which is part of angularjs
I have read through this question ASP.NET MVC DropDownListFor not selecting value from model and answer but I don't know the solution to my problem.
This is part of my controller, here is first time when I call the ddl for the view, but not yet select any value.
private void bindDDLRefund(FormModel mod){
// refundCodes = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).Select(e => e.RefundCode).FirstOrDefault();
mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).ToList().Select(e => new SelectListItem { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString() }).OrderBy(e => e.Value);
//mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted == false).ToList().Select(e => new SelectListItem() { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString(), Selected = (e.RefundCode == mod.RefundCode) }).ToList();
}
public ActionResult Add(){
var mod = new FormModel();
//var percentage = GetAllPercentage();
//mod.ddlRefundPercentage = GetSelectListItems(percentage);
bindDDLRefund(mod);
mod.isCreate = true;
return View("Form",mod);
}
Then here is the selected value is being selected from controller,
public JsonResult GetTicketData(string ticketnumber){
bool isSuccess = false;
var result = new spRefTicketRefundRetrieve();
int isError = 0;
string errorDesc = "";
var mod = new FormModel();
try{
spRefTicketRefundRetrieveHeader obj = _uow.StoreProc.spRefTicketRefundRetrieve(ticketnumber);
isError = obj.IsError;
errorDesc = obj.ErrorDesc;
if (obj.IsError == 0){
result = obj.detailData;
}
isSuccess = true;
}
catch (Exception ex){
Logger.LogError("Reload Ticket Data", "Id = " + ticketnumber, ex);
}
return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetRefundData(string refund_id)
{
bool isSuccess = false;
var result = new spRefTicketRefundDetail();
int refundId = Encryption.Decrypt(refund_id);
try
{
result = _uow.StoreProc.spRefTicketRefundDetail(refundId);
isSuccess = true;
}
catch (Exception ex)
{
Logger.LogError("Reload Refund Data", "Id = " + refundId, ex);
}
return Json(new { success = isSuccess, value = result }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetCFData(string ticketNumber, string refundCode)
{
bool isSuccess = false;
var result = new spRefTicketRefundChangeCF();
int isError = 0;
string errorDesc = "";
try
{
spRefTicketRefundChangeCFHeader obj = _uow.StoreProc.spRefTicketRefundChangeCF(ticketNumber, refundCode);
isError = obj.IsError;
errorDesc = obj.ErrorDesc;
if (obj.IsError == 0)
{
result = obj.listData;
}
isSuccess = true;
}
catch (Exception ex)
{
Logger.LogError("Reload CF Data", "Id = " + ticketNumber, ex);
}
return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
}
The selected value is about CfPercentage and variable result contains CF_PERCENTAGE which is representate of CfPercentage,
And here is my view and jQuery;
#Html.DropDownListFor(e => e.RefundCode, Model.DdlRefundPercentage, new { #class = "form-control", id= "ddl-refund",onchange="CFChange();" })
var GetRefundData = function (refundId) {
$.ajax({
url: '#Url.Action("GetRefundData")',
type: 'POST',
data: { refund_id: refundId },
success: function (result) {
console.log(result);
if (result.success) {
SetFormDetail(result.value);
}
else
{
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var GetRefundViewData = function (refundId) {
$.ajax({
url: '#Url.Action("GetRefundData")',
type: 'POST',
data: { refund_id: refundId },
success: function (result) {
console.log(result);
if (result.success) {
SetFormView(result.value);
}
else {
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var GetTicketData = function (ticketNumber) {
var target = $("#loading");
$.ajax({
beforeSend: function () {
target.html('<img src="#Url.Content("~/Content/images/ajax-loader.gif")"> loading...');
$('#divForm').css('display', 'none');
},
url: '#Url.Action("GetTicketData")',
type: 'POST',
data: { ticketnumber: ticketNumber },
success: function (result) {
console.log(result);
if (result.success) {
target.html('');
if (result.isError == "0") {
$('#divForm').css('display', 'block');
$('#txtHiddenTicketNumber').val(ticketNumber);
SetForm(result.value);
GetCFData();
}
else {
alert(result.errorDesc);
}
}
else {
$("#loading").html('');
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var CFChange = function ()
{
GetCFData();
};
var GetCFData = function ()
{
var TicketNumber = $('#txtHiddenTicketNumber').val();
var RefundCode = $("#ddl-refund option:selected").val();
$.ajax({
url: '#Url.Action("GetCFData")',
type: 'POST',
data: { ticketNumber: TicketNumber, refundCode: RefundCode },
success: function (result) {
console.log(result);
if (result.success) {
SetCFDetail(result.value);
}
else {
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var SetForm = function(list){
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.TICKET_USED);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#txtReason').val('');
$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR);
});
};
var SetFormDetail = function (list) {
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.USED_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#txtReason').val(this.DESCRIPTION);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
//$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
$("#ddl-refund").val(this.REFUND_CODE);
});
//GetCFData();
};
var SetFormView = function (list) {
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.USED_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#lblPaymentType').html(this.PAYMENT_TYPE);
$('#lblReason').html(this.DESCRIPTION);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
//$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
$("#ddl-refund").val(this.REFUND_CODE);
});
//GetCFData();
};
var SetCFDetail = function (list) {
$(list).each(function () {
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
});
};
After I running this, the view is always not select percentage based on sp that is relevant to ticketnumber. I have tried to modified it but nothing works. feel happy to be help :)
This line,
$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR)
It actually set's the currently selected option's text to whatever value in this.CANCELLATION_FEE_PERCENTAGE_STR . It won't actually change the selected option. You can see it in action here.
What you should be doing Get the RefundCode value from your server call, and pass that in the val() method to set specific option item as the selected item.
Assuming your razor rendered your dropdown with this markup.
<SELECT id="ddl-refund">
<option value="25">Twenty Five</option>
<option value="26">Twenty Six</option>
<option value="28">Twenty Eight</option>
<option value="29">Twenty Nine</option>
And json data you received from your server call has a property called RedundCode.
$(list).each(function () {
$("#ddl-refund").val(this.RefundCode);
}
It will work if this.RefundCode is either 25 or 26 or 28 or 29.
I am not quite sure, why you are sending an array when all you want to send is a single item. But that is a different thing to fix.
Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});
I've got the following Sharepoint problem: I've created a Ribbon Button, which says "Read Only". When I am on a list, and check some items, I want to set those items to read only.
The ribbon button works great and when I am doing an alert or something, I get an answer. So this cannot be the problem. I did the following:
var listitem;
var roleAssgn;
var Assgn;
var selectedItems;
function readonly() {
selectedItems = SP.ListOperation.Selection.getSelectedItems();
var currentListGuid = SP.ListOperation.Selection.getSelectedList();
var context = SP.ClientContext.get_current();
var currentWeb = context.get_web();
var currentList = currentWeb.get_lists().getById(currentListGuid);
for (k in selectedItems) {
listitem = currentList.getItemById(selectedItems[k].id);
context.load(listitem, 'RoleAssignments');
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerItem), Function.createDelegate(this, this.failed));
}
}
function readonlyPerItem(sender, args) {
var k;
var Assgn;
var r;
context = SP.ClientContext.get_current();
roleAssgn = listitem.get_roleAssignments();
for(r in roleAssgn){
Assgn = roleAssgn[r];
alert("1");
context.load(Assgn, 'RoleDefinitionBindings');
alert("2");
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerRoleA), Function.createDelegate(this, this.failed));
}
}
function readonlyPerRoleA(sender, args) {
var bindings = Assgn.get_roleDefinitionBindings();
var member = Assgn.get_member();
}
function failed(sender, args) {
alert("FAIL");
}
This works great until it gets to the alerts. Alert-1 is working, but not Alert-2. The Debugger says: The object does not support the property "get_$h".
And that happens in the sp_runtime.js with:
SP.DataRetrievalWithExpressionString.$1Q_0(a.get_$h(),d)
I dont really see a problem. Is this a bug or is it just not possible?
Ok, I used another way to do this and wanted to let you know, how it worked for me. I used a JS in the Ribbon Menu to call another website, which is just an empty site. I added the parameters (listguid, siteurl and the itemid's comma-seperated).
Then that site just prints an "True" or "False". This response will be caught by my Ribbon JS and show some message if it worked or not. This is my Ribbon JS:
<CustomAction
Id="ReadOnlyButton"
RegistrationId="101"
RegistrationType="List"
Location="CommandUI.Ribbon"
Sequence="15"
Rights="ManageLists"
Title="Set Readonly">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Documents.Manage.Controls._children">
<Button
Id="Ribbon.Documents.ReadOnly"
Command="ReadOnly"
Sequence="15"
Image16by16="/_layouts/1031/images/formatmap16x16.png"
Image16by16Left="-80"
Image16by16Top="-128"
Image32by32="/_layouts/1031/images/formatmap32x32.png"
Image32by32Left="-160"
Image32by32Top="-256"
Description="Read Only"
LabelText="Read Only"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="ReadOnly"
CommandAction="javascript:
var nid;
function getItemIds()
{
var itemIds = '';
var items = SP.ListOperation.Selection.getSelectedItems();
var item;
for(var i in items)
{
item = items[i];
if(itemIds != '')
{
itemIds = itemIds + ',';
}
itemIds = itemIds + item.id;
}
return itemIds;
}
function handleReadyStateChange()
{
if (client.readyState == 4)
{
if (client.status == 200)
{
SP.UI.Notify.removeNotification(nid);
if(client.responseText == 'True') {
nid = SP.UI.Status.addStatus('The Rights has been set successfully', '', true);
SP.UI.Status.setStatusPriColor(nid, 'green');
} else {
nid = SP.UI.Status.addStatus('Error while setting Rights', '', true);
SP.UI.Status.setStatusPriColor(nid, 'red');
}
window.setTimeout('SP.UI.Status.removeStatus(\'' + nid + '\')', 5000);
}
}
}
function invokeReadOnly()
{
var itemLength = 0;
var params = 'itemids=' + getItemIds();
for (var i=0;i<params.length;i++) { if (',' == params.substr(i,1)) { itemLength++; } }
if(itemLength > 0) {
nid = SP.UI.Notify.addNotification('Rights set for ' + (itemLength +1) + ' elements...', true);
} else {
nid = SP.UI.Notify.addNotification('Set Rights...', true);
}
var site='{SiteUrl}';
var url = site + '/_layouts/ReadOnly.aspx?listId={ListId}';
client = null;
client = new XMLHttpRequest();
client.onreadystatechange = handleReadyStateChange;
client.open('POST', url, true);
client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
client.setRequestHeader('Content-length', params.length);
client.send(params);
}
invokeReadOnly();"
EnabledScript="javascript:
function enableReadOnly()
{
var items = SP.ListOperation.Selection.getSelectedItems();
return (items.length > 0);
}
enableReadOnly();"/>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
And this is my site behind it (ReadOnly.aspx):
protected void Page_Load(object sender, EventArgs e)
{
string itemidsAll = Page.Request["itemids"];
string listId = Page.Request["listId"];
bool set = true;
if (!String.IsNullOrEmpty(itemidsAll))
{
string[] itemIds = itemidsAll.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int item = 0;
SPSite _site = null;
SPListItem spitem = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
_site = new SPSite(SPContext.Current.Site.ID);
});
using (SPWeb web = _site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList doclib = SPContext.Current.Web.Lists.GetList(new Guid(listId), false);
foreach (string itemId in itemIds)
{
if (Int32.TryParse(itemId, out item))
{
spitem = doclib.GetItemById(item);
set &= SetItem(spitem, SPContext.Current, ref _site);
}
}
web.AllowUnsafeUpdates = false;
}
_site.Dispose();
}
Response.Clear();
Response.Write(set.ToString());
Response.End();
}
The SetItem-Method is for setting the Rights. You can use your own stuff there :)