controller action execute two times with Ajax.ActionLink and JQuery UI Dialog - javascript

I have ajax.actionlink
#Ajax.ActionLink("Click here",//link text
"Insert", // action name
"Projects", // controller
new { poz = item.itemID.ToString() }, // route values
new AjaxOptions() { HttpMethod = "GET", UpdateTargetID = "PrjDiv" OnSuccess = "Initiate_Dialog" }, // ajax options
new { #class = "openDialog", #id = item.idemID.ToString() } //htmlAttributes
)
and jQuery UI dialog
function Initiate_Dialog() {
var itemID= $(this).attr("id").replace("item_", "");
var prjID= $("#m_project").val();
var url = encodeURI("/Projects/Insert?poz=" + itemID+ "&proj=" + prjID);
$("#dialog-edit").dialog({
title: 'Insert',
autoOpen: false,
resizable: false,
height: 'auto',
width: 650,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
},
buttons: {
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#dialog-edit").dialog('open');
return false;
}
When i click on generated link, my controller action is executed 2 times. Once with parameters sent from ajax.actionlink, and second time, with parameters sent from javascript.
I know that i have 2 calls and that's why is action executed twice. My question is, is there a way around this to execute only call from javascript, and not from actionlink?

Related

How to call fucntion when modal close JQuery

I need to call a function when modal close. My code as follows,
function openModal(divName) {
$("#"+divName+"Modal").modal({
overlayClose: false,
closeHTML: "<a href='#' title='Close' class='modal-close'>X</a>",
onShow: function (dialog) {
$('#simplemodal-container').css({ 'width': 'auto', 'height': 'auto', 'padding-bottom': '1000px' });
var tmpW = $('#simplemodal-container').width() / 2
var tmpH = $('#simplemodal-container').height() / 2
$('#simplemodal-container').css({ 'margin-left': tmpW * -1, 'margin-top': tmpH * -1 });
},
close:onClose,
onClose: ModalClose(),
opacity: 50,
persist: true
});
}
I tried two ways to call a function as follows, but both not working
1st way
function onClose() {
alert('called');
}
2nd way
$('.resetbutton').click(function () {
alert('called');
}
Call another function which you want inside ModalClose(), if it user-defined function
From the bootstrap documentations, you can just call the javascript event on closing the modal Javascript.Bootstrap
$('#myModal').on('hide.bs.modal', function (e) {
// do the closing function...
});
And for Kendo Library you can do the close but without the "()" and this will pass the event "e" in the function
close: onClose,
Events in Kendo UI
dialog.kendoDialog({
width: "400px",
title: "Software Update",
closable: true,
modal: false,
content: "<p>A new version of <strong>Kendo UI</strong> is available. Would you like to download and install it now?<p>",
actions: [
{ text: 'Close', action: onCancel },
{ text: 'OK', primary: true, action: onOK }
],
initOpen: onInitOpen,
open: onOpen,
close: onClose,
show: onShow,
hide: onHide
});
function onClose(e) {
show.fadeIn();
kendoConsole.log("event :: close");
}

Ajax.BeginForm() post method not returning Partial View

I have a MVC application and I'm trying to insert properties of objects. For that, I made a modal popup via jQuery dialog. I don't want it interfering with other actions that the user is doing, so I made an Ajax.BeginForm. I hoped that when I do the insert, it will close on return PartialView(), but it opens the popup View on full screen instead of closing the dialog. Also, it is important that the base view should be dynamic, so you can open the dialog on any page and not make a postback.
I've read the other similar issues and couldn't resolve my problem.
There are some similar issues, but none of them
Please, help me to achieve the proper function if possible. Code below:
JS:
<script>
$(document).ready(function () {
var url = "";
$("#dialog-alert").dialog({
title: 'Error encountered!',
autoOpen: false,
resizable: false,
width: 350,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true
});
if ('#TempData["msg"]' != "") {
$("#dialog-alert").dialog('open');
}
$("#lnkServer").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new Server" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#lnkIssType").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new Issue Type" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#lnkUser").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new User" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#lnkDept").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new Department" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#dialog-edit").dialog({
autoOpen: false,
resizable: false,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
//$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
}
//buttons: {
// "Cancel": function () {
// $(this).dialog("close");
// }
//}
});
});
function onSuccess() {
$("#dialog-edit").dialog('close');
}
</script>
Form:
<div id="container">
#using (Ajax.BeginForm("AddDept", new AjaxOptions { OnSuccess = "onSuccess" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div>
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Department_Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Department_Name, htmlAttributes: new { #class = "form-control text-box single-line input-properties", placeholder = "Collections" })
</div>
<div class="editor-label">
#Html.ValidationMessageFor(model => model.Department_Name)
</div>
<input type="submit" value="Submit" class="btn btn-default btn-add-properties" />
</fieldset>
</div>
}
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDept([Bind(Include = "Department_Name")] Department #dept)
{
try
{
if (ModelState.IsValid)
{
db.Departments.Add(#dept);
db.SaveChanges();
TempData["Msg"] = "Data has been saved successfully";
return PartialView();
//return Redirect(System.Web.HttpContext.Current.Request.UrlReferrer.PathAndQuery);
}
}
catch
{
TempData["Msg"] = "Probably the record already exists. If not, contact Georgi Georgiev, RA Dept.";
return PartialView();
}
return PartialView(#dept);
}
My problem was probably due to that my Ajax.BeginForm popup View relied on different ActionResult in the controller compared to the Background View's.
Anyway, it turns out that I couldn't achieve my functionality without having a POST through Ajax.
Here's what I did (in Layout view):
$("#dialog-edit").dialog({
autoOpen: false,
resizable: false,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
//$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
},
buttons: [{
text: "Submit",
"class": "btn-add-properties",
click: function () {
var form = $('form', this);
$.post(form.prop('action'),
form.serialize(),
function (response) {
alert("success");
})
.fail(function () {
alert("error");
});
$("#dialog-edit").dialog('close');
}
}]
});
The ajax post is the function under the dialog button.

Problems with appear confirm window when closing dialog?

When I add the card to the in box. Then it is possible to double click on the card, and dialog pop up. In the dialog I have Tow buttons (Save) and (Cancel). When I press Cancel buttons a confirm window pop-ups.
I want when I press the close in the right corner, that confirm window pop-ups. I tried by this part of code to fix it, but not succeeded:
close: function () {
$('#dialog-confirm').dialog({
resizable: false,
height: 300,
modal: true,
draggable: false,
buttons: {
YES: function () {
$(this).dialog("close");
$('#modalDialog').dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
The issue is when I'm doing it in that way, the dialog window first close, then the confirm window pop-up. I don't want that, but I want the opposite.
JQuery:
$(function () {
// Click function to add a card
var $div = $('<div />').addClass('sortable-div');
$('<label>Title</label><br/>').appendTo($div);
$('<input/>', { "type": "text","class":"ctb"}).appendTo($div);
$('<input/>', { "type": "text","class":"date"}).appendTo($div);
var cnt =0,$currentTarget;
$('#AddCardBtn').click(function () {
var $newDiv = $div.clone(true);
cnt++;
$newDiv.prop("id","div"+cnt);
$('#userAddedCard').append($newDiv);
// alert($('#userAddedCard').find("div.sortable-div").length);
});
// Double click to open Modal Dialog Window
$('#userAddedCard').dblclick(function (e) {
$currentTarget = $(e.target);
$('#modalDialog').dialog({
modal: true,
height: 600,
width: 500,
position: 'center',
buttons: {
Save: function () { //submit
var val = $("#customTextBox").val();
$currentTarget.find(".ctb").val(val);
$currentTarget.find(".date").val($("#datepicker").val());
$('#modalDialog').dialog("close");
},
Cancel: function () { //cancel
$('#dialog-confirm').dialog({
resizable: false,
height: 300,
modal: true,
draggable: false,
buttons: {
YES: function () {
$(this).dialog("close");
$('#modalDialog').dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
},
close: function () {
$('#dialog-confirm').dialog({
resizable: false,
height: 300,
modal: true,
draggable: false,
buttons: {
YES: function () {
$(this).dialog("close");
$('#modalDialog').dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
});
});
$("#datepicker").datepicker({showWeek:true, firstDay:1});
});
Maybe I'm wrong, in that way I'm doing. Any idea how to fix it?
Live Demo
You may try use the beforeClose for the confirm window, and if confirmed then close the dialog.

How to close a jQuery dialog after an AJAX JSON call

I am using ASP.NET MVC 4, jQuery, and jQuery UI.
I have a dialog on my view. When I click a button the dialog pops up, takes the values on the dialog and send its through to a service. The service does what it needs to do and will either send back a blank message if it is successful or the actual error message. After this I need to check the error on the client side, close the current dialog and open a success dialog or the error dialog. I'm not sure how to close the current dialog and to display another dialog.
My button:
<button id="TestButton" type="button">Display pop up</button>
My dialogs:
<div id="confirmationDialog"></div>
<div id="successDialog"></div>
<div id="errorDialog">error dialog</div>
my jQuery code:
$('#TestButton').click(function () {
$('#confirmationDialog').dialog('open');
});
$('#errorDialog').dialog({
autoOpen: false,
modal: true,
resizable: false,
width: 500,
title: 'Add Rule Detail Error',
buttons: {
'Ok': function () {
$(this).dialog('close');
}
}
});
$('#confirmationDialog').dialog({
autoOpen: false,
modal: true,
resizable: false,
width: 330,
title: 'Add Rule Detail Confirmation',
open: function (event, ui) {
$(this).load('#Url.Action("AddRuleConfirmation")' +
'?systemCode=' + $('#SystemCode').val());
},
buttons: {
'Yes': function () {
var url = '#Url.Action("AddRuleConfirmationSubmit")';
var data = {
systemCode: $('#SystemCode').val()
};
$.getJSON(url, data, function (message) {
alert(message);
if (message == '') {
$(this).dialog('close');
}
else {
$(this).dialog('close');
$('#errorDialog').dialog('open');
}
});
},
'No': function () {
$(this).dialog('close');
}
}
});
My action methods:
public ActionResult AddRuleConfirmation(string systemCode)
{
DetailConfirmationViewModel viewModel = new DetailConfirmationViewModel()
{
SystemCode = systemCode
};
return PartialView("_AddRuleConfirmation", viewModel);
}
public ActionResult AddRuleConfirmationSubmit(string systemCode)
{
CreateRuleViewModel viewModel = new CreateRuleViewModel()
{
SystemCode = systemCode
};
ResCodeRuleAdd_Type result = ruleService.AddRule(viewModel);
string message = string.Empty;
if (result != ResCodeRuleAdd_Type.R00)
{
// Get the error message from resource file
message = ...
}
return Json(message, JsonRequestBehavior.AllowGet);
}
How do I close the current pop up after the get JSON call and open another?
You have to add the dialog to the page first: Put this prior to your current:
$('#errorDialog').dialog({
autoOpen: false,
modal: true,
resizable: false,
width: 330,
title: 'My Error Dialog'
});
//current code follows:
$('#confirmationDialog').dialog({
Then what you have should work.
EDIT: I thought about this a bit, you probably need to fix the scope of the $(this) inside the success handler.
change to do:
var myDialog = $('#confirmationDialog').dialog({
and then use:
myDialog.dialog('close');
inside that handler to close the first dialog.
In the getJSON callback close the window
$.getJSON( "test/demo", function( data) {
if(data==='success'){
$( ".selector" ).dialog( "close" );
$( ".selector" ).dialog( "open" );
}
});
To close the jquery UI dialog use this
$( ".selector" ).dialog( "close" );
Top Open a new dialog
$( ".selector" ).dialog( "open" );
for more info check the api of jquery UI http://api.jqueryui.com/dialog/#method-close
var dialogAviso;
url = "search.php";
$.ajax( {
"type": "POST",
"url": url,
"data": data,
"global": false,
"async": true,
"success": function(html){
msg_title ="Search";
msg_width = "600px";
showDialog(html,msg_title,msg_width);
}
} );
function showDialog(texto, titulo, width,height){
.......................
// IMPORTANT: send info to the aux variable, so you can access it from the dialog.
dialogAviso = $('#divaviso').dialog({
autoOpen: true,
width: width,
height:height,
modal:true,
resizable: false,
title: titulo,
dialogClass: 'dialog',
closeOnEscape:true,
beforeClose: function(){
},
close: function(event, ui) {
$(this).dialog( "destroy" );
},
show: "slide",
zindex: 100,
stack:true,
buttons: {}
});
$('#divaviso').html(texto);
}
search.php:
<table>
<tr>
<td><a style=\"text-decoration:underline;cursor:pointer;\" onclick="returnInfo(8)">Hello World</td>';
</tr>
</table>
functin returnInfo (id){
// Do something with the selected item
// close dialog
dialogAviso.dialog("close");
}

Passing a value into a jQuery UI dialog box with a function

This is my document.ready code:
$(document).ready(function() {
$("#dialogbox").dialog({
open: function(event, ui) {$("a.ui-dialog-titlebar-close").remove();},
bgiframe: true,autoOpen: false,closeOnEscape: false,draggable: false,
show: "drop",hide: "drop",zIndex: 10000,modal: true,
buttons: {'Ok': function() {$(this).dialog("close");processEmp();}}
});
});
I have the following JavaScript code that takes one parameter:
function test(pEmp)
{
var a = pEmp.value);
$('#dialogbox').dialog('open');
}
My question is, based on the value that I pass into my test function, which in turn calls my jQuery UI dialog ('#dialogbox'), when the user presses the 'Ok' button in the dialog, I need to somehow (which is what I am not sure how to do), pass the the variable "a" which holds my pEmp.value, into my other function processEmp(a?), which I have attached to my 'Ok' button.
I basically need this value when the user acknowledges the dialog box.
You may pass custom option to dialog before opening it:
$(function () {
$("#dialog").dialog({
open: function (event, ui) { $("a.ui-dialog-titlebar-close").remove(); },
bgiframe: true,
autoOpen: false,
closeOnEscape: false,
draggable: false,
show: "drop",
hide: "drop",
zIndex: 10000,
modal: true,
buttons: { 'Ok': function () {
$(this).dialog("close");
processEmp($(this).data("pEmpValue"));
}
}
});
});
function processEmp(a) {
alert(a);
}
function test(pEmp) {
$("#dialog").data("pEmpValue", pEmp.value).dialog("open");
}
Or even the simplest solution is to declare a variable in scope of the window:
var a = null;
$(function () {
$("#dialog").dialog({
open: function (event, ui) { $("a.ui-dialog-titlebar-close").remove(); },
bgiframe: true,
autoOpen: false,
closeOnEscape: false,
draggable: false,
show: "drop",
hide: "drop",
zIndex: 10000,
modal: true,
buttons: { 'Ok': function () {
$(this).dialog("close");
processEmp(a);
}
}
});
});
function processEmp(a) {
alert(a);
}
function test(pEmp) {
a = pEmp.value;
$("#dialog").dialog("open");
}
You can achieve this by adding an event handler for 'close'. Something like this:
$("#dialogbox").bind("dialogclose", function(event, ui) { processEmp(a); });

Categories

Resources