set buffer false during jQuery ajaxSubmit - c#

I want to run ASPX page in ASP page.
So I use ajaxSubmit and print to "target div" get from ASPX page like this:
var data = new FormData();
data.append("email", $("#EMAIL").val());
data.append("pass", $("#PASS").val());
data.append("store", $("#STORE").val());
if ($("#STORE").val()!="" && $("#EMAIL").val()!="" && $("#PASS").val()!="") {
e.preventDefault();
$(this).ajaxSubmit({
data: $(this).serialize(),
target: "#formres",
async: true,
global: false,
cache: false,
beforeSubmit: function () {
},
success: function () {
if($("#yu").val()!="yes")
{
setTimeout(function(){
window.location.href = $("#yu").val();
},2000);
}
},
resetForm: false
});
But anything display before process ends.
I think it must be something like "Response.Buffer=false" or "flush()" at jquery too.(I use "cache: false," for this purpose)
I set Reponse.Buffer =false at asp and aspx page.
But it still not working. Could anyone help me?

Related

asp-all-route-data not calling action method in Asp.Net Core MVC

I am running Asp.Net Core 3.1 application where i have one left side menu in layout which i load through partial view.
To set menu link i used the anchor tag like below:
var allRouteData = new Dictionary<string, string>
{
{ "menuid", mID.ToString() },
{ "isCalledByMenu", "true" },
{ "where", "tab" }
};
<a class="#clas" data-ajax="true" data-ajax-complete="RedirectToPage('#M.MenuUrl', '#M.MenuName',true)" data-ajax-mode="replace" data-ajax-update="#myTab" asp-action="GetSubMenu" asp-controller="Base" asp-all-route-data="#allRouteData">#M.MenuName</a>
So when page loads then HTML generate like below:
<a class="nav-link btn fuse-ripple-ready" data-ajax="true" data-ajax-complete="RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services',true)" data-ajax-mode="replace" data-ajax-update="#myTab" href="/Base/GetSubMenu?menuid=9630&isCalledByMenu=true&where=tab">Professional Services</a>
Below is action method used :
public IActionResult GetSubMenu(int menuid, bool? isCalledByMenu, string where = null)
{
return ViewComponent("SubMenu", new { menuid = menuid, isCalledByMenu = isCalledByMenu, where = where });
}
In Layout page on the top i assigned the tag helper:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
But when i click on the link it is not hitting this action method.
Update: When i click menu then first it hit the list inside javascript where i do some ajax call:
$('#myTab>li>a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
e.preventDefault();
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
In SetCurrentPageNameSession method i do ajax call to set the menu name in server side to some session before calling action method.
like below:
function SetCurrentPageNameSession(CurrentPage, IsBookMark) {
if (IsBookMark==undefined)
IsBookMark = false;
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark },
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
Then after it anchor tag call the action method.
Please suggest.
Maybe you could forget data-ajax, it also doesn't work on me and I can't find the answer about it. You could code as below and it also can request the GetSubMenu and continue to excute next logic.
<div id="myTab"></div>
<a class="nav-link btn fuse-ripple-ready"
href="#">Professional Services</a>
<script>
$('a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
//e.preventDefault();
$.ajax({
url: "/Base/GetSubMenu",
async: true,
type: "get",
datatype: "json",
data: #Json.Serialize(allRouteData),
success: function (result) {
$('#myTab').html(result)
}
});
//RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services', true);
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
</script>
Comment or Remove e.preventDefault();
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
I found the solution for the above asked question:
The issue was when i click on menu link then i used to call first it's anchor click in javascript where i did e.preventDefault() and then used to do some ajax call to pass some value to set in session. Due to e.preventDefault() call after that it was not hitting the action method.
Since i had to pass other three data to server to set somewhere. To do that i set all three value in anchor tag data-link attribute separated with Pipe like below:
data-link="9630|true|tab|/OrgOverview/ProfessionalServices|Professional Services"
function SetCurrentPageNameSession(CurrentPage, IsBookMark, MenuID, IsCalledByMenu, Where, PageUrl, PageName) {
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark, menuID: MenuID, isCalledByMenu: IsCalledByMenu, where: Where},
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
if (PageUrl != undefined && PageUrl != '' && PageUrl != null)
RedirectToPage(PageUrl, PageName, true, false)
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Then in this ajax call success i am redirecting the page with passed page url.
But still i am wondering the same code how it was working in MVC and not in asp.net core.
That's it.

Adding a script to a page on exit using Ajax. The script loads, but doesn't work through the ajax method?

When the users try to exit the page, I want to load a new script into my page.
The script successfully gets adding to the page, but it simply doesn't work properly. Now, if I just put the script into my page from the get-go, not using ajax, it does work. To me, this makes absolutely no sense, but something in my method/jQuery is clearly screwing the script up.
Lines from the JS file which Ajax doesn't seem to like:
document.write('<div id="' + token + '"></div>');
that.div.style.position = 'relative';
Error includes
Uncaught TypeError: Cannot read property 'style' of null
I'm assuming it's related to the script not being loaded onload? :S
This is my code
My Web Method.
[WebMethod]
public string webcamLink(string cat)
{
string script = "<script src=\"thescipt.js\"></script>";
return script;
}
This is my jQuery.
setTimeout(() => {
$(document).on("mouseout", evt => {
if (evt.toElement === null && evt.relatedTarget === null) {
$(evt.currentTarget).off("mouseout");
// An intent to exit has happened
$("#myNav").css("display", "block");
var cat = "cat";
var t = JSON.stringify({
'cat': cat
});
$.ajax({
type: "POST",
url: '/webServices/pop-up.asmx/webcamLink',
data: t,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 15000,
async: true
});
}
});
}, 5000);
function OnSuccess(data) {
$('#cams').html(data.d);
};
And my HTML:
<div id="cams" class="container-fluid"></div>
Does anybody have any idea what I'm doing wrong? I apologise if I'm being silly, quite new to this.

Setting form values when jQuery datatable row is clicked

I have a web form with a jQuery datatable in it. When a particular row is clicked I get the row data and need to set the values of the controls on the page.
I can get the row values, I set breakpoints and can see the row values fetched are correct but for some reason the control values don't get set (for example, a label's text). This is what I have (watered down version):
$(document).ready(function () {
var zTable = $("#fcTable").DataTable({
"bServerSide": true,
"bDestroy": true,
"sAjaxSource": "../fc.asmx/GetItems",
"bJQueryUI": true,
"fnServerParams": function (aoData) {
aoData.push({ "name": "FacilityID", "value": $('#<%= ddlFacility.ClientID %> option:selected').val() });
},
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#fcTable").show();
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
alert(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
}
});
$('#fcTable tbody').on('click', 'tr', function () {
var currentRowData = zTable.row(this).data();
processRow(currentRowData);
});
})
function processRow(row) {
debugger
$("#<%= rblResp.ClientID %> input[type=radio]").prop('checked', false);
$("#<%= cblResp.ClientID %> input[type=checkbox]").prop('checked', false);
var sQuestion = row[2];
// None of these sets the label's text
$('#<%= lblQuestion.ClientID %>').val(sQuestion);
$('#<%= lblQuestion.ClientID %>').innerHTML = sQuestion;
}
Update
I can get it to work using
$('#<%= lblQuestion.ClientID %>')[0].innerHTML = sQuestion;
i.e. adding an array index [0].
But is this the correct way of doing it?
The issue is that $('#<%= lblQuestion.ClientID %>') returns a jQuery object, and innerHTML is standard JavaScript, and won't work as wanted on a jQuery object.
The [0] on the end of the object gives you the DOM node (first property of the object), which is what innerHTML needs.
The correct way to do it in pure jQuery would be just:
$('#<%= lblQuestion.ClientID %>').html(sQuestion);
FYI, you can set ClientIDMode="Static" on the input, to avoid asp.Net overriding the ID you give it in your HTML, and so avoid all the <%=... stuff in your JavaScript, which works much better if you get to the point where you want to split the JavaScript out into its own file.

Use jQuery Select2 with ASP.NET MVC

I'm trying to use Select2 in Razor in ASP.NET MVC. But I can't get work.
$(document).ready(function () {
$(".genreOptions").select2({
tags: true,
ajax: {
url: 'http://localhost:65148/NewProfile/Genres',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.Id, //id part present in data
text: item.Genre //string to be displayed
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1
});
#Html.DropDownListFor(x => x.BandProfile.Genres, Enumerable.Empty<SelectListItem>(), new { #class="genreOptions", multiple = "multiple", style ="width: 100%;"} )
The searching for tags works fine. But when I post the form, the count of the input field Is 0. How can I capture the data from the input form?
#Bryan I build up a javascript array and pass it with ajax to the server. Seems to work ok for my purposes. Perhaps you could try that. The selectors I put below will be different than what you need but here is the general idea...
On Click
$('#submitButton').click(function () {
fillHiddenInput();
var dataToSend = $('#hiddenInput').val();
//Submit the form with ajax or however you want to get dataToSend to server
});
FillHiddenInput function...
var fillHiddenInput = function () {
$('#hiddenInput').val("");
var stuff = [];
$('.ms-selection .ms-list li ul').children('li').each(function (){
if ($(this).hasClass('ms-selected'))
{
stuff.push($(this).children('span').text());
}
});
$('#hiddenInput').val(stuff);
}

Fancybox doesn't work after a success of an ajax call

Why is not working fancybox after check validation in c#?
fancybox is call after use PageMethods.ValidacionIsAdmin(onSuccessValidacionIsAdmin); if it is valid the return of database executed in:
[WebMethod]
public static DeleteAccountResult ValidacionIsAdmin()
{
DeleteAccountResult res = new DeleteAccountResult();
... // Query to database with ok results
res.ok = true;
return res;
}
The ajax call in client to validate it is:
jQuery(".delete a").click(function () {
function onSuccessValidacionIsAdmin(data) {
if (data.ok == true) {
jQuery("#<%= divError.ClientID %>").hide();
jQuery(".delete a").fancybox({
content: jQuery('#eliminar-cuenta').html(),
modal: false,
showCloseButton: false,
onComplete: function () {
jQuery("input[type=checkbox]").uniform()
jQuery('#privacidad').fancybox({
enableEscapeButton: false,
hideOnOverlayClick: false,
showCloseButton: true,
onComplete: function () {
jQuery('#fancybox-close').off().on('click', function (e) {
e.preventDefault();
jQuery(".delete a").click();
});
}
});
}
});
}
else {
jQuery("#<%= divError.ClientID %>").show();
jQuery("#lblError")[0].innerHTML = data.strError;
}
}
PageMethods.ValidacionIsAdmin(onSuccessValidacionIsAdmin);
});
The Behaviour is look like after to push the link which open fancybox don't open it, looks like it "refresh" the web and I push the same link and then it is working...
I readed fancy doesn't work after an ajax call (in my case the c# validation)
My question is: why it happens?
After some hours of investigation, I got the solution. It is curious, in all propierties ineas to write content: ... I replaced as: 'content': ...
I added the property 'type':'html'
After do that the fancybox was working.
jQuery(".delete a").fancybox({
'content': jQuery('#eliminar-cuenta').html(),
'type': 'html',
'modal': false,
'showCloseButton': false,
'onComplete': function () {
jQuery("input[type=checkbox]").uniform()
jQuery('#privacidad').fancybox({
enableEscapeButton: false,
hideOnOverlayClick: false,
showCloseButton: true,
onComplete: function () {
jQuery('#fancybox-close').off().on('click', function (e) {
e.preventDefault();
jQuery(".delete a").click();
});
}
});
}
});

Categories