How to block targetUpdateId using Blockui using ajax.actionLink or ajax.beginForm - asp.net-mvc

I want to develop an ajax pipeline such that whenever there is any ajax request made through ajax.beginform or ajax.actionLink it should start with my ajax.start function in which i can be able to read the targetupdateid so that i can shoew blockui and any developer should not bother about this ajax.start.I was trying to use this piece of code but itis not working
$(document).ajaxStart(function (xhr, setting) {
console.log(this.activeElement);
if (this.activeElement.type == 'submit') {
activeElement = this.activeElement.form.attributes["data-ajax-update"].value;
} else {
/ activeElement = this.activeElement.attributes["data-ajax-update"].value;
}
if (activeElement != null) {
$(activeElement).blockUI();
}
});
Any help would highly be appreciated.

try this
<div id="mainbody">
</div>
<div id="SomeId" style="display:none">
// put you style to block the UI here
// or put loader image
<img src="#Url.Content("~/Content/themes/base/images/ajax_loader_big.gif")" alt="" />
</div>
#Ajax.BeginForm("Index", "Search", new AjaxOptions { UpdateTargetId = "mainbody", HttpMethod = "Post", LoadingElementId = "SomeId" })
you can use Ajax-Loader or some css style with loader image which will block the UI. you need to paas that div Id in LoadingElementId which block the UI until ajax functionality is not completed.

Thanks for the solution but i want to block the UpdateTargetId which i resolve by adding a listener to the click .
var activeElement,
targetElement,
callbackfunc = function (event) {
activeElement = event.target || event.srcElement;
};
window.addEventListener('click', callbackfunc, true);
$(document).ajaxStart(function () {if (activeElement !== null && activeElement !== undefined) {
if (activeElement.type == 'submit') {
targetElement = activeElement.form.attributes["data-ajax-update"].value;
}
if (activeElement.tagName == 'A') {
targetElement = activeElement.attributes["data-ajax-update"].value;
}
}
if (targetElement !== undefined || targetElement !== null) {
$(targetElement).block({
showOverlay: false,
css: { border: '0px', width: '40px', height: '40px' },
message: '<div class="progress"><div>'
});
}
});

Related

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

CKEditor not working after opening jQuery UI Dialog

I have a jQuery UI Dialog that has a CKEditor instance on it. I can open the dialog and interact fine with the editor. But if I open another jQuery UI dialog from the original dialog the text in the editor disappears when the second dialog opens and the editor can't be used until you reload the entire page.
This works fine if the CKEditor instance is not in a dialog. I can open up the child dialog, use it, close it, and still interact with editor.
Any ideas what is going on and how to make it work?
Sample program below or http://jsfiddle.net/3EyM4/1/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.3.2/ckeditor.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.3.2/adapters/jquery.js"></script>
</head>
<body>
<script>
$(document).ready(
function()
{
$('textarea').ckeditor( { toolbar: [] } );
$( "#childDialog" ).dialog(
{
autoOpen: false
} );
$( "#parentDialog" ).dialog(
{
autoOpen: false
} );
});
</script>
<div>
Main page
<button onclick="$('#parentDialog').dialog( 'open' );">Open Parent</button>
</div>
<div id="parentDialog" title="Parent Dialog">
<button onclick="$('#childDialog').dialog( 'open' );">Open Child</button>
<textarea name="editorTextArea"></textarea>
</div>
<div id="childDialog" title="Child Dialog">
Child
</div>
</body>
</html>
You need to instantiate the CKEDITOR on the open event of the dialog
open: CKEDITOR.replace('editor1', {
height: 145,
width: 500,
allowedContent: true,
}),
Then is will allow text. Something to do with the Iframe that CKEDITOR uses
This will work fine
Check CKEditor intances than destroy it when dialog is closed. Enjoy your code
function DestryoCKEditorInstances(textarea_name)
{
if (CKEDITOR.instances[textarea_name])
{
CKEDITOR.instances[textarea_name].destroy();
}
}
$( "#add-task" ).dialog({
modal: true,
minHeight: 600,
minWidth: 600,
position: [0,28],
create: function (event) { $(event.target).parent().css('position', 'fixed');},
open: CKEDITOR.replace('textarea_name',{language: 'tr',height: 150,width: 550, allowedContent: true}),
close: function (){
DestryoCKEditorInstances('textarea_name');
form[ 0 ].reset();
},
buttons: {
"Add Task": function() {
Add();
form[ 0 ].reset();
$( this ).dialog( "close" );
},
"Keep Going To Add Task": function() {
Add();
form[ 0 ].reset();
},
Cancel: function() {
form[ 0 ].reset();
$( this ).dialog( "close" );
}
}
});
I found a workaround at least. If I save the contents of the editor and destroy the instance before opening the dialog, and then recreate the editor instance after opening the dialog, it all works fine.
var editor = $('textarea').ckeditorGet();
editor.updateElement();
editor.destroy();
$('#childDialog').dialog( 'open' );
$('textarea').ckeditor( { toolbar: [] } );
I had a similar problem loading text into ckeditor while it was inside a jquery ui dialog. I had 2 instances of ckeditor and an ajax post to get the data so my workaround was:
(...)
success: function(data, textStatus, jqXHR) {
for (name in CKEDITOR.instances) {
CKEDITOR.instances[name].destroy()
}
$('#newForm').dialog('open');
$("#dialog").focus();
$('#txtDescription').ckeditor({ toolbar: 'Basic' });
$('#txtDescriptionFr').ckeditor({ toolbar: 'Basic' });
CKEDITOR.instances['txtDescription'].setData(data.Description.NameEn);
CKEDITOR.instances['txtDescriptionFr'].setData(data.Description.NameFr);
}
To get around the Problems when having a CKEDITOR in a Jquery ui-dialog I did the following:
Problem 1:
Dropdowns like font-size etc. arent visible in ckeditor.
Solution:
config.baseFloatZIndex=9999999;
Problem 2:
Input Fileds in CKEDITOR Dialog arent "active".
Solution:
Close ui-dialog when ckeditor dialog opens and vice-versa
Problem 3:
Ckeditor dialog input fields arent "active" when ckeditor switches to fullscreen mode
Solution:
Close jquery ui-dialog when ckeditor is going to fullscreen, reopen when leaving fullscreen mode
My CKEDITOR jquery adapter now looks like this, works fine for me:
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function(a) {
if ("undefined" == typeof a) throw Error("jQuery should be loaded before CKEditor jQuery adapter.");
if ("undefined" == typeof CKEDITOR) throw Error("CKEditor should be loaded before CKEditor jQuery adapter.");
console.error("CKEDITOR jQuery Team-pro adapter v0.4a");
CKEDITOR.config.jqueryOverrideVal = "undefined" == typeof CKEDITOR.config.jqueryOverrideVal ? !0 : CKEDITOR.config.jqueryOverrideVal;
a.extend(a.fn, {
ckeditorGet: function() {
var a = this.eq(0).data("ckeditorInstance");
if (!a) throw "CKEditor is not initialized yet, use ckeditor() with a callback.";
return a
},
ckeditor: function(g, d) {
if (!CKEDITOR.env.isCompatible) throw Error("The environment is incompatible.");
if (!a.isFunction(g)) {
var m = d;
d = g;
g = m
}
var k = [];
d = d || {};
this.each(function() {
var b = a(this),
c = b.data("ckeditorInstance"),
f = b.data("_ckeditorInstanceLock"),
h = this,
l = new a.Deferred;
k.push(l.promise());
if (c && !f) g && g.apply(c, [this]), l.resolve();
else if (f) c.once("instanceReady", function() {
setTimeout(function() {
c.element ? (c.element.$ == h && g && g.apply(c, [h]), l.resolve()) : setTimeout(arguments.callee, 100)
}, 0)
},
null, null, 9999);
else {
if (d.autoUpdateElement || "undefined" == typeof d.autoUpdateElement && CKEDITOR.config.autoUpdateElement) d.autoUpdateElementJquery = !0;
d.autoUpdateElement = !1;
b.data("_ckeditorInstanceLock", !0);
c = a(this).is("textarea") ? CKEDITOR.replace(h, d) : CKEDITOR.inline(h, d);
b.data("ckeditorInstance", c);
c.on("instanceReady", function(d) {
var e = d.editor;
e.config.baseFloatZIndex=9999999;
setTimeout(function() {
if (e.element) {
d.removeListener();
e.on("dataReady", function() {
b.trigger("dataReady.ckeditor", [e])
});
e.on("setData", function(a) {
b.trigger("setData.ckeditor", [e, a.data])
});
e.on("getData", function(a) {
b.trigger("getData.ckeditor", [e, a.data])
}, 999);
e.on("destroy", function() {
b.trigger("destroy.ckeditor", [e])
});
e.on("save", function() {
a(h.form).submit();
return !1
}, null, null, 20);
if (e.config.autoUpdateElementJquery && b.is("textarea") && a(h.form).length) {
var c = function() {
b.ckeditor(function() {
e.updateElement()
})
};
a(h.form).submit(c);
a(h.form).bind("form-pre-serialize", c);
b.bind("destroy.ckeditor", function() {
a(h.form).unbind("submit", c);
a(h.form).unbind("form-pre-serialize",
c)
})
}
e.on("destroy", function() {
b.removeData("ckeditorInstance")
});
/*
e.on("maximize", function (e) {
// console.log('---------------------------- MAXIMIZE ----------------------------');
// console.debug(e.data);
switch(parseInt(e.data)){
case(1)://Gehe in Fullscreen, SCHLIESSE Jquery ui Dialoge
console.log('CKEDITOR [maximize:true] jQuery adapter: schliesse ui-dialog');
$('.ui-dialog-content').dialog('close');
break;
case(2)://Gehe in Fullscreen, OFFNE Jquery ui Dialoge
console.log('CKEDITOR [maximize:false] jQuery adapter: öffne ui-dialog');
$('.ui-dialog-content').dialog('open');
break;
}
});
*/
b.removeData("_ckeditorInstanceLock");
b.trigger("instanceReady.ckeditor", [e]);
g && g.apply(e, [h]);
l.resolve()
} else setTimeout(arguments.callee, 100)
}, 0)
}, null, null, 9999)
}
});
var f = new a.Deferred;
this.promise = f.promise();
a.when.apply(this, k).then(function() {
f.resolve();
CKEDITOR.on("dialogDefinition", function (e) {
var dialogName = e.data.name;
var dialog = e.data.definition.dialog;
dialog.on('show', function () {
console.log('CKEDITOR [dialogdefinition:true] jQuery adapter: schliesse ui-dialog');
$('.ui-dialog-content').dialog('close');
});
dialog.on('hide', function () {
console.log('CKEDITOR [dialogdefinition:false] jQuery adapter: öffne ui-dialog');
$('.ui-dialog-content').dialog('open');
});
});
});
this.editor = this.eq(0).data("ckeditorInstance");
return this
}
});
CKEDITOR.config.jqueryOverrideVal && (a.fn.val = CKEDITOR.tools.override(a.fn.val, function(g) {
return function(d) {
if (arguments.length) {
var m =
this,
k = [],
f = this.each(function() {
var b = a(this),
c = b.data("ckeditorInstance");
if (b.is("textarea") && c) {
var f = new a.Deferred;
c.setData(d, function() {
f.resolve()
});
k.push(f.promise());
return !0
}
return g.call(b, d)
});
if (k.length) {
var b = new a.Deferred;
a.when.apply(this, k).done(function() {
b.resolveWith(m)
});
return b.promise()
}
return f
}
var f = a(this).eq(0),
c = f.data("ckeditorInstance");
return f.is("textarea") && c ? c.getData() : g.call(f)
}
}))
})(window.jQuery);
Also found this solution:
https://forum.jquery.com/topic/can-t-edit-fields-of-ckeditor-in-jquery-ui-modal-dialog

jQuery autocomplete completely unresponsive

This is my first time really delving into jQuery with my ASP MVC3 intranet app. I need the autocomplete to be able to reference a list of items from a database. I followed the tutorial found here and thought "ok, that looks easy"... and now after implementing the code and researching other methods and bashing my head against the keyboard for at least four hours I'm not anywhere closer to making this work that before I wrote the code.
Here is the code from the view, w/the library declarations as well. FYI - I am taking over this project, so all the other javascript/Ajax you see was written by someone else with more experience than me. I put all the code in this section just in case something else is getting in the way.
<link href="../../Content/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#BankName").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
$(function () {
$("#drpProducerType").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#Role").val(value);
$('#DSSfields').removeClass('noSee');
$('#DSSfields').addClass('seeMe');
//alert("Role must be set to \"Sole Proprietor\" as well. Monet will do this for you!");
}
else {
//TO DO: add role stuff here as well
$('#DSSfields').removeClass('seeMe');
$('#DSSfields').addClass('noSee');
}
});
$("#Role").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#drpProducerType").val(value);
alert("Producer Type changed to \"Sole Proprietor\" as well");
}
});
});
function ChangeChannel() {
//this function called if Market Segment changes, to update the channel
var pendistcode = document.getElementById('Pendist');
if (pendistcode == null) alert('Error: Cannot find Market Segment control');
$.ajax({
type: 'POST',
url: '/AgentTransmission/GetChannel/',
data: { pendist: pendistcode.value },
success: function (data) {
// alert("success: " + data);
$('#channelName').html(data);
$('#Channel').val(data);
},
error: function (data) {
alert("failure to obtain Channel name");
}
});
CheckTerritory('channel');
} //end ChangeChannel
function CheckTerritory(category) {
//this function called when changes happen that could change the territory (inddist)
//if the channel changed, or the alignment indicator, update the Territory
if ((category == "channel") | (category == "align")) UpdateTerritory();
//only trigger if the state or zip changed on the aligned address
if ((category == "L") && ($('#AlignmentL').attr('checked'))) UpdateTerritory();
if ((category == "M") && ($('#AlignmentM').attr('checked'))) UpdateTerritory();
} //end CheckTerritory
function UpdateTerritory() {
var i = $('#INDDist').val();
var p = $('#Pendist').val();
// alert(":" + i + ":" + p + ":");
//if ((i == "") || (p == "")) return;
if (p == "") return;
if ($('#INDDist').val() == "864") {
$('#INDDist').val("701");
}
else {
if ($('#INDDist').val() == "") {
$('#INDDist').val("864");
}
}
} //end UpdateTerritory
function MoreCompanies(row) {
//if the user clicks on the plus sign, add more company rows
if (row == '3') {
$('#plus2').html(' ');
$('#row3').removeClass('noSee');
$('#row3').addClass('seeMe');
}
if (row == '4') {
$('#plus3').html(' ');
$('#row4').removeClass('noSee');
$('#row4').addClass('seeMe');
}
if (row == '5') {
$('#plus4').html(' ');
$('#row5').removeClass('noSee');
$('#row5').addClass('seeMe');
}
} //end MoreCompanies
function CompanyFields() {
} //end CompanyFields
function ShowHideTerritory() {
alert('sunshine');
} //end ShowHideTerritory
</script>
The text box the autocomplete is supposed to work on
<div class="M-editor-label">
Bank\Agency Name
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.BankName, new { id = "BankName" })
#Html.ValidationMessageFor(model => model.BankName)
</div>
and here is the GetBanks method from the controller. I've set a breakpoint at the first line of this method and I've never been able to get it to hit.
//GET
public JsonResult GetBanks(string search)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(search))
select c.BankName;
banks = banks.Distinct();
return Json(banks, JsonRequestBehavior.AllowGet);
}
EDIT
If I replace the current .autocomplete code with the code suggested by this method instead , I get the following error in Chrome's debugger:
Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method '/AgentTransmission/GetBanks'
Here's the new code, I put it in the exact same spot as what I was previously using:
$(document).ready( function() {
$('#BankName').autocomplete('#Url.Action("GetBanks", "AgentTransmission")', {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].BankName };
}
return rows;
},
formatItem: function(row, i, n) {
return row.BankName + ' - ' + row.Description;
},
width: 300,
mustMatch: true,
});
});
I added an extra set of closing brackets to the autocomplete which cleared this up. The widget functions properly now.
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
});

How I can clear textbox text before ajax form submit event?

I want to clear textbox after ajax posting.
<div style="padding: 5px; background-color: Silver;">
#using (Ajax.BeginForm("_MessagesPartial", "Chat", new AjaxOptions { UpdateTargetId = Model.room_id.ToString() }))
{
<div style="padding: 5px 15px 5px 5px;">
#Html.TextBox("textbox_message", null, new { #class = "text_yorum", id = "text_box_chat" })
#Html.Hidden("oda_id", Model.room_id)
</div>
}
</div>
<div id="#Model.room_id" style="height:400px;overflow-y:scroll;position: relative;">
#Html.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id })
</div>
there are a lot of example, but they do not work. I m already using this code, but it is too slow.
$("form").submit(function () {
$.get('#Url.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id }) ', {}, function (view) {
$("##Model.room_id").html(view);
$("#text_box_chat").val("");
});
});
Is there any way to do this.
I usually use the Ajax function. But anyways I believe the key to your problem is that you have no success function. Try something like this.
$.ajax({
url: 'yourfile.php',
type: 'POST',
success: function() {
$('#myform input').val("");
}
});
You seem to be sending 2 AJAX requests. One sent by the Ajax.BeginForm helper and one inside your custom .submit handler. You could specify a callback which will be executed after the AJAX request completes in the AjaxOptions:
#using (Ajax.BeginForm("_MessagesPartial", "Chat", new AjaxOptions { UpdateTargetId = Model.room_id.ToString(), OnSuccess = "onSuccess" }))
{
...
}
and clear the input inside this callback:
function onSuccess() {
$("#text_box_chat").val("");
}
You don't need to subscribe to the .submit event of the form as you did and send an AJAX request. That's what the Ajax.BeginForm helper already does.

using iscroll with jquerymobile

I am building an app using jquerymobile in phonegap. I am using he following code to achieve fixed header, footer, scrollable content using iscroll.js. The problem is that I am unable to scroll the content div. Pls help me.
enter code here<body onload="loaded()">
<div data-role="page" id="detail">
<div class="fixedHeader">
</div>
<div id="wrapper" >
<div id="scroll-content">
<div data-role="content">
<!-- dynamic content goes here -->
dynamic content goes here
</div>
</div>
</div>
<div class="fixedFooter" ></div>
</div>
#wrapper {
position:absolute; z-index:1;
top:45px; bottom:48px; left:0;
width:100%;
overflow:auto;
}
#scroller {
position:relative;
/* -webkit-touch-callout:none;*/
float:left;
width:100%;
padding:0;
}
Javascript code
var myScroll;
function loaded() {
myScroll = new iScroll('wrapper', {
onBeforeScrollStart: function (e) {
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
e.preventDefault();
}
});
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);
i got iscroll working in jquerymobile by editing js as
var myScroll = [];
$(document).delegate('[data-role="page"]', 'pageshow', function () {
var $page = $(this);
// setup iScroll
$($page.find('#wrapper')).each(function(index) {
var scroller_id = $(this).get(0);
myScroll.push(
new iScroll(scroller_id, {
useTransform: false,
onBeforeScrollStart: function (e) {
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT'&& target.tagName !='option'&& target.tagName !='option' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
e.preventDefault();
e.stopPropagation();
}
}));
});
});
$(document).delegate('[data-role="page"]', 'pagehide', function () {
// unset and delete iScroll
for (x in myScroll)
{
myScroll[x].destroy();
myScroll[x] = null;
myScroll.splice(x, 1);
}
});
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

Resources