Show confirm dialog from code behind ASP.NET - c#

I want to show confirm dialog from code be hind.
I have a comfirm dialog A. when I click button OK on A, it was call to the method B in code be hind(using ajax post: url/B and B is a method has webmethod attribute).
In method B I want to show other dialog, and code is flowing:(B is AlertInformLogOut )
[WebMethod]
public static void AlertInformLogOut(string alertId, string option)
{
//TODO: Open call schedule
var page = HttpContext.Current.Handler as Page;
// PopUp alert notify info
if (page != null)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "script", "AlertSetDialog(" + new JavaScriptSerializer().Serialize(new AlertInformEntity()) + ", 'AlertInforms');", true);
//ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "script", "AlertSetDialog(" + new JavaScriptSerializer().Serialize(new AlertInformEntity()) + ", 'AlertInforms');", true);
}
}
problem is: Dialog not showing.
Can some body tell me why, and can I showing dialog from a method has webmethod attribute.

The problem is, as I recall, a WebMethod wont update the page, unlike an ASP:update panel call back.
As you are using jQueries ajax function, use the success call back there, instead of trying to do it server side.
$.ajax({
type: "POST",
url: url+"/UpdateAlertInfo",....,
success: /*Call you Confirm Function Here */
}
You may alss want to consider using $.post() insteado

Related

Why does my function stop working without an alert?

So I've got this function right here in my view:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
});
alert('Izbrisan'); #* bez ovoga se ne brise proizvod *#
}
}
The controller it's passed to:
public ActionResult izbrisiProizvod(int Id)
{
RadniProizvod.IzbrisiProizvod(Id);
return View();
}
And finally the "IzbrisiProizvod" method:
public void IzbrisiProizvod(int IdProizvoda)
{
Proizvod izbrisaniProizvod = azilEntities.Proizvods.FirstOrDefault(x => x.idProizvoda == IdProizvoda);
azilEntities.Proizvods.Remove(izbrisaniProizvod);
azilEntities.SaveChanges();
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Can someone explain this magic to me?
Always write your jquery functions like this, as per documentation. (The always is optional)
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
So in your case:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
}
}
And maybe change alerts to console log or similar.
Try Network tool within your browser dev tools. For example for Firefox Dev Tools. When you click your element (let's say button) you should see new http request in the list of all request within Network tool. If you don't then your ajax call didn't happen at all or it was happen on previous page because you've experienced page reloading. Check if Proizvod actually deleted. If it is then your js function works but you don't see response. If there is s new http request within Network tool, inspect it a little bit to see what is happen (just click on it and in the right you will see details).
Also, you can open console and instead click the html element type in your console: izbrisi(). Function should execute and if it works you will see a new http request in Network tool and your alert for done will popup. If this is the case then your html element has default behavior on click event. So you should prevent it in order to prevent page reloading. Let say that you use a button for click on it. The button html should look like:
<button onclick="izbrisi(e)">Izbrisi</button>
And the js function:
function izbrisi(e) {
e.preventDefault();
// ... your code goes here
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Your ajax only contains the .done() promise callback. This will only execute if the ajax request receives a 200 success code. You can add in the .fail() promise to with a unique alert to see what is happening.
In your code, the final alert is fired no matter what.
Try this to help see what is going on. Use this fiddle and open your console also. Note the different alert messages in the .done() and .fail() promises.
//var b = document.getElementById('proizvod')?.value;
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: {
id: 'someData'
}
}).done(function() {
alert('success');
}).fail(function() {
alert('error');
});
console.log('i fire no matter what');

jQuery modal dialog first open works, subsequent opens fail

I've got an MVC project written in C# using Razor Engine. I'm calling a modal through jQuery which loads a form to POST fields to my controller via AJAX, returning updated content that loads into the calling DIV.
This works wonderfully ... once. Attempting to open the modal again (to edit a different row), the form loads into the browser as if redirected, rather than displaying it in a modal dialog.
In my view, I'm calling my modal from a link (Custom HTML Helper, line breaks added only for readability):
#Html.NoEncodeActionLink("<span class='glyphicon glyphicon-pencil'></span>", "Edit Phone", "Edit", "PhoneLinks",
theseRouteValues: new { id = item.id },
theseHtmlAttributes: new {
data_modal = "",
data_toggle = "modal",
data_dismiss = "modal",
data_title = "Edit Phone",
data_btnlabel = "Edit Phone",
data_callingdiv = "replaceTargetPhone",
data_whichform = "PhoneLinkModalForm",
#class = "btn btn-primary btn-xs"
}
)
Clicks on the link are caught in my jQuery and handled there with AJAX.
jQuery(function () {
jQuery.ajaxSetup({ cache: false });
// Initialize the modal DIV
var $modalDiv = jQuery("<div class='modalContent'></div>")
.appendTo('body')
.dialog({
modal: true,
autoOpen: false,
position: { my: 'center', at: 'center', collision: 'fit' },
show: { effect: 'blind', duration: 300 },
hide: { effect: 'explode', duration: 500 },
close: function () { jQuery('div.modalContent').empty(); }
});
// Create a modal popup when a modal-generating link is clicked
jQuery("a[data-modal]").on("click", function (e) {
e.preventDefault();
// Gather parameters from the link into variables for readability
var sourceLink = jQuery(this);
var sourceHref = sourceLink.attr('href'); // Relative path to controller method
var titleData = sourceLink.data('title'); // Title for the modal dialog
var callingDiv = "#" + sourceLink.data('callingdiv'); // #replaceTarget divs ... where to apply refresh after AJAX returns
var whichForm = "#" + sourceLink.data('whichform'); // ID of the form called by the link that will be submitted in the modal
var btnProceed = sourceLink.data('btnlabel'); // Which function was called: Create/Edit/Delete (for button labelling)
var btnCancel = "Cancel";
var theseButtons = {};
// Submit Button
theseButtons[btnProceed] = function () {
// Send parameters to another function for processing
// On success, the processForm() function closes the modal
processForm(theModalContent, callingDiv, theModalContainer, sourceHref, whichForm, titleData);
};
// Cancel Button
theseButtons[btnCancel] = function () {
jQuery('div.modalContent').empty().dialog('close');
return false;
};
// Add a few parameters to the modal (title, buttons, etc.) and load content
$modalDiv.empty();
$modalDiv
.load(sourceHref)
.dialog({
title: titleData,
buttons: theseButtons
});
$modalDiv.dialog('open');
});
});
The processForm() function handles the AJAX call to the controller, and it works as expected. On success, it closes the modal with the same line of code in the Cancel button:
jQuery('div.modalContent').empty().dialog('close');
I can open the modal the first time without issue.
First call to modal works perfectly.
I can cancel the modal and reopen it as many times as I want.
If I submit the form in the modal, the form is processed correctly, my database updates correctly, and the content reloads in the target DIV correctly. However, if I then try to open a subsequent modal (for editing another phone number), the form doesn't load into a modal. It instead loads as the body of a new HTML document.
Second call to modal fails.
I have tried closing the modal in many different ways:
.dialog('destroy')
or
.remove()
or
.dialog('destroy').remove()
I have also tried initializing the modal within the "a[data-modal].on('click') function, rather than initializing on document ready.
All working variations work the first time, then fail after the first submit.
Any suggestions are greatly appreciated!
UPDATE: Added processForm() function code.
function processForm(thisModalContent, thisCallingDiv, thisModalContainer, thisMethod, thisForm, thisTitle) {
// Capture the form fields
var formPost = jQuery(thisForm);
// Serialize the fields to an array
// This step is necessary to handle phone number mask removal
var values = formPost.serializeArray();
// Some code here removes phone masking and
// puts the raw numbers back into the array
// Convert the serialized array to a single string for POST
var serializedPost = jQuery.param(values);
// Send data to controller and handle response
jQuery.ajax({
url: thisMethod,
type: 'POST',
data: serializedPost,
error: function (x, e) {
if (x.status === 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status === 404) {
alert('Requested URL not found.');
} else if (x.status === 500) {
alert('Internal Server Error.\n DataSent: \n' + serializedPost + '\n Response Text: \n' + x.responseText);
} else if (e === 'parsererror') {
alert('Error.\nParsing JSON Request failed.\n' + x.responseJSON);
} else if (e === 'timeout') {
alert('Request Time out.');
} else {
alert('Unknown Error.\n' + x.responseText);
}
},
success: function (result) {
if (result.success) {
//jQuery('div.modalContent').dialog('destroy').remove(); // Didn't Work
//jQuery('div.modalContent').dialog('destroy'); // Didn't Work
//jQuery('div.modalContent').remove(); // Didn't Work
jQuery('div.modalContent').empty().dialog('close');
jQuery(thisCallingDiv).load(result.url);
} else {
thisModalContent.html(result);
}
}
});
return false;
}
Also, it's worth mentioning that while the code in this example is referencing phone numbers, I have a DIV for addresses on the same page. The Address editing link click calls the same jQuery modal.
If I submit a phone edit, subsequent calls to the modal from phone edit links are broken.
BUT I can successfully call the address edit modal ... once. Then subsequent calls to it are broken.
Refreshing the page fixes the modal from both link types (phones and addresses). Both types can be opened and cancelled repeatedly until one is submitted. Then that one is broken, but the other still works until it is submitted.

Ajax call gets cached, despite the appropriate parameter

I'm currently writing a MVC C# application. Everything works just fine. I have a bit of functionality, where I fill up a Bootstrap modal box using an Ajax call, but the new page gets cached, despite my efforts to prevent that.
On my main page I have the following actionhandler to fill up the modal box:
function setExtraPermsOrAtts(appID){
$.ajax({
cache:false,
url: "/Group/_modifyAppPermissionsOfGroup?appID=" + appID
}).done(function (result) {
$("#addApplicationBody").html(result);
$('#modal-add-application').modal('show');
});
}
This gets caught by the following method:
public ActionResult _modifyAppPermissionsOfGroup(int? appID = 0)
{
if (appID != 0)
{
ViewBag.selectedAppID = appID;
Session["selectedGroupAppID"] = appID;
ViewBag.modifyPermsLater = true;
}
Group group = (Group)Session["currentGroup"];
return View(group);
}
Another thing that might be relevant is the point where it 'goes wrong'. The resulting View in the Modalbox, has a few radio buttons, depending on the content of the database. There I do a razor statement to get the DB value:
bool valueOfRadButtons = BusinessLogic.Domain.GroupIS.getExistingGroupPermission(
Model.LoginGroupID, myItem.ApplicationPermissionID).LoginPermissionState;
Does anyone know where I'm going wrong? Is it the Ajax call? The ActionResult method in the Controller? Or the inline razor statement? I know the data gets saved properly, cause I see so in the DB
You can specify that the response shouldn't be cached like this:
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
It can be more easy if you make your own attribute and decorate the action with it as shown here.

update field or redirect page using jquery and asp.net mvc

Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Calling a code behind method based on a click event

I currently have this working but it requires me to have a static method as the method called in the code behind. I would like to be able to access some member variables that can't be static. I'm not married to the Javascript implementation and am open to other suggestions that would help me achieve this.
If there is other information that would be helpful let me know and I can include.
EDIT: Let me clarify, I'm looking to edit a value in one of the user controls on the page based on the button click. I am holding the user controls in a list on the page and using the parameters passed through the javascript to find the user control that I want to update and modify the value there.
It currently looks like this:
Javascript:
function incrementCompletes(obj)
{
var firstParameter = $(obj).parents('.parentClass1').find('.childClass1').html();
var secondParameter = $(obj).parents('.parentClass2').find('.childClass2').html();
var parameters = "{'firstParam':'" + firstParameter+ "','secondParam':'" + secondParameter+ "'}";
$.ajax({
type: "POST",
url: "Page.aspx/StaticMethod",
contentType: "application/json; charset=utf-8",
data: parameters,
dataType: "json",
success:
function DoOtherStuffHere(result) {
var x = $(obj).parents('.classWithStuffToChange');
var y = $(x).find('.otherClassWithStuffToChange');
y[0].innerHTML=" + " + result.d;
}
});
}
Code behind:
[WebMethod]
public static int StaticMethod(string parameter1, string parameter2)
{
//Do some stuff
//Return a value
}
I would like to find a solution that does not require the method called to be static.
If you want to access member varaibles of the page, there has to be an instance of the page class. That means that you have to do a postback instead of calling a web method.
Use a regular Button control, that will cause a postback and you can use it's Click event to run a method in the code behind. If you don't want the page to be reloaded, you can use ASP.NET AJAX to do the callback using AJAX.

Categories