ASP.NET MVC 4 JQuery Dialogs - javascript

I want to modify the javascript from an ASP.NET MVC 4 template website so that the dialogs that comes with the template to login/register actions could be used in any link that had an ".ajax-link" class in my code. So I did some changes in AjaxLogin.js that now looks like this:
//...
$('.ajax-link').each(function () {
$(this).click(function (e) {
var link = $(this),
url = link.attr('href');
var separator = url.indexOf('?') >= 0 ? '&' : '?';
$.get(url + separator + 'content=1')
.done(function (content) {
var dialog = $('<div class="modal-popup"">' + content + '</div>')
.hide() // Hide the dialog for now so we prevent flicker
.appendTo(document.body)
.filter('div') // Filter for the div tag only, script tags could surface
.dialog({ // Create the jQuery UI dialog
dialogClass: 'fi-dialog',
title: link.data('dialog-title'),
modal: true,
resizable: false,
draggable: true,
width: link.data('dialog-width') || 600,
beforeClose: function () { resetForm($(this).find('form')); }
})
.find('form') // Attach logic on forms
.submit(formSubmitHandler)
.end();
dialog.dialog('open');
});
// Prevent the normal behavior since we use a dialog
e.preventDefault();
});
});
//...
And then I add the attribute class="ajax-link" in all the links I want to be shown in an jQuery dialog.
But it's not working. Actually the dialog opens only to the FIRST link I click inside the page, and after I close the dialog I can click in any other link that it won't appear. What I'm doing wrong here?

Actually you only need 2 very slight modifications to the AjaxLogin.js script to make this work.
The first modification is towards the end of the file where you have an array of selectors. All you have to do is add your .ajax-link selector:
// List of link ids to have an ajax dialog
var links = ['#loginLink', '#registerLink', '.ajax-link'];
and the second modification is inside the resetForm function in order to add a check if there's a form before attempting to reset it. Because if there isn't a form inside the partial you are rendering you will get an error when you attempt to close the dialog:
var resetForm = function ($form) {
// make sure that there's a form before attempting to reset its elements
if ($form.length < 1) {
// No form inside the partial => we have nothing more to do here
return;
}
// We reset the form so we make sure unobtrusive errors get cleared out.
$form[0].reset();
getValidationSummaryErrors($form)
.removeClass('validation-summary-errors')
.addClass('validation-summary-valid')
};
Now you can have:
#Html.ActionLink(
"Foo",
"foo",
null,
new { #class = "ajax-link", data_dialog_title = "hello" }
)
with a corresponding action:
public ActionResult Foo()
{
// return a PartialView or whatever you want to popup in the dialog
return Content("hello world from a jQuery Dialog");
}
and it will show the result of the Foo action inside a dialog, exactly the same way it does for the LogOn and Register actions.

$('.ajax-link').each(function () {
$(this).click(function (e) {
var link = $(this),
url = link.attr('href');
var separator = url.indexOf('?') >= 0 ? '&' : '?';
//clear all cashed dialog form
$("div.modal-popup").remove();
.
.
.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Scripts/css/ui-lightness/jquery-ui-1.8.16.custom.css" rel="stylesheet"
type="text/css" />
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.16.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var UIDialogId = 0;
$('.UIDialogOpen').live('click', function (e) {
e.preventDefault();
UIDialogId++;
$('<div/>', {
'id': $(this).attr('data-dialog-id') !== undefined ? $(this).attr('data-dialog-id') : 'UIDialog' + UIDialogId,
'class': 'UIDialog'
}).appendTo('body').dialog({
title: $(this).attr('data-dialog-title') !== undefined ? $(this).attr('data-dialog-title') : 'Message',
position: ['center', 'center'],
modal: true, resizable: false, zIndex: 10000, autoOpen: true,
minWidth: $(this).attr('data-dialog-minwidth') !== undefined ? $(this).attr('data-dialog-minwidth') : '300px',
minHeight: $(this).attr('data-dialog-minheight') !== undefined ? $(this).attr('data-dialog-minheight') : '300px',
maxWidth: $(this).attr('data-dialog-maxwidth') !== undefined ? $(this).attr('data-dialog-maxwidth') : '300px',
maxHeight: $(this).attr('data-dialog-maxheight') !== undefined ? $(this).attr('data-dialog-maxheight') : '300px',
close: function (event, ui) {
$(this).remove();
}
})
//.load(this.href);
//Or //Use .load(this.href); and comment or delete below append line.
.append('<h1>Hi.. This is Testing </h1> <input type="button" class="UIDialogCancel" value="Cancel" /> <input type="button" class="UIDialogClose" value="Close" />');
$('.UIDialogClose, .UIDialogCancel').live('click', function (e) {
var obj = $(this)
e.preventDefault();
obj.parents('.UIDialog').dialog('close');
});
});
});
</script>
</head>
<body>
<a href="http://3.bp.blogspot.com/-atcX8smV6wA/T5ULj6LU4fI/AAAAAAAAAFg/oK08hPLOmWI/s1600/between.png"
class="UIDialogOpen" data-id="bloger">Bloger</a>
<br />
<div>
#Html.ActionLink("ActionLinkName", "MethodeName", "ControllerName", new { Id =2
}, new { #class = "UIDialogOpen", data_dialog_title = "UI Dialog Message" })
</div>
<div>
#Html.ActionLink("ActionLinkName", "MethodeName", "ControllerName", null, new {
#class = "UIDialogOpen", data_dialog_title = "UI Dialog MEssage" })
</div>
</body>
</html>

Related

how to remove jquery modal form and keep it as simple html form at the bottom of page

how to remove this jquery dialog and show it as a simple html form at the bottom of web page when clicked on button. I've a bootstrap table when i click on the add new record button it shows dialog modal but i want to make it simple html form without pop up
$(function () {
var new_dialog = function (type, row) {
var dlg = $("#dialog-form").clone();
var email = dlg.find(("#email")),
password = dlg.find(("#password"));
type = type || 'Create';
var config = {
autoOpen: true,
height: 400,
width: 450,
modal: true,
buttons: {
"Create an account": save_data,
"Cancel": function () {
dlg.dialog("close");
}
},
close: function () {
dlg.remove();
}
};
if (type === 'Edit') {
config.title = "Edit User";
get_data();
delete(config.buttons['Create an account']);
config.buttons['Edit account'] = function () {
row.remove();
save_data();
};
}
dlg.dialog(config);
Not sure if it works, but try. Set false to modal property, and add position and top properties in config;
modal: false,
position: 'relative',
top: 0,
Or, in html code delete the class attribute of the Div with the modal content.

jQuery ("#dialog").dialog('close') not working with button on separate view

I have an ASP.NET view in an MVC project in which I am trying to create a pop-up dialog to create data. There is another view that gets loaded and that view has a button with the id "btncancel_create". I cannot get that button to close the dialog. I am using jQuery 2.1.3 and jQuery UI 1.11.4.
Here is the code for the button:
<input type="button" value="Cancel" id="btncancel_create" />
And here is the view:
$(document).ready(function () {
//alert("Document is ready");
var url = "";
$("#dialog-create").dialog({
title: 'Create User',
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);
}
});
$("#lnkCreate").on("click", function (e) {
url = $(this).attr('href');
$("#dialog-create").dialog('open');
return false;
});
//$("#btncancel_create").on("click", function (e) {
// $("#dialog-create").dialog("close");
// return false;
//});
$("#dialog-create").button("#btncancel_create").click(function (e) {
alert("btncancel_create was clicked");
$("#dialog-create").dialog('close');
return false;
});
});
<div id="dialog-create" style="display: none"></div>
<p>#Html.ActionLink("Create New", "Create", null, new { id = "lnkCreate" })</p>
As you can see, I tried something else which didn't work, which is commented out. The uncommented button click function does return the alert, but does not close the dialog. Thanks in advance for your help, and please let me know if you need any more information.
Instead of
$("#btncancel_create").on("click", function (e) {...
(in my commented out code above)
it should be
$(document).on("click", "#btncancel_create", function (e) {....
I found the answer here: Turning live() into on() in jQuery.

Can't load AJAX content in jQuery dialog

I got this dynamically created JQueryUI dialog from this thread that loads content via Ajax from <a href='2.html'>. But I found there is an issue with the following code. Even though AJAX request is successfully made as shown in Console, the content isn't able to append to the dialog container. Can anyone find out what's problem with the load function at this line:
dialog.load($(this).attr('href') + ' #content').dialog
I have tried
dialog.append($(this).data('source') + ' #content').dialog
dialog.text($(this).data('source') + ' #content').dialog
and they work.
Code:
var loading = $('<img src="http://upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" alt="loading" class="loading">');
$(document).ready(function () {
$(document).ready(function () {
$('button').click(function () {
$(this).next('.area').append('<a id="open_dia_'+Date.now().toString()+'" class="open_dia" title="this title" href="2.html">Click</a>');
});
$(document).on('click', '.open_dia', function (evt) {
var dialogid = 'dialog_'+$(this).attr('id');
var dialog = null;
if ($('#'+dialogid.toString()).length == 0)
{
dialog = $('<div id="'+dialogid+'"></div>').append(loading.clone());
dialog.load($(this).attr('href') + ' #content').dialog({
title: $(this).attr('title'),
width: 500,
height: 300
});
}
else
{
dialog = $('#'+dialogid.toString());
}
dialog.dialog('open');
return false;
});
});
You can do it in this way:
Create a div, and a div inside that you'll use it to append the content.
<div id="dialogDiv" title="this title" style="display:none;">
<div id='dialogDivDynamic'></div>
</div>
convert your first div in the dialog:
$("#selectionResult").dialog({
modal: true,
width: '900px',
buttons: [{ text: "Close", click: functionToCloseDialog() }]
});
append the content to your second div:
$('#dialogDivDynamic').append("This is my new content");
function functionToCloseDialog() {
$('#dialogDiv').dialog('close');
}
It seems that there is an space before your hash... Try this way:
dialog.load($(this).attr('href') + '#content').dialog({
title: $(this).attr('title'),
width: 500,
height: 300
});

How to trigger OnClick and OnClientClick events simultaneously in ASP.NET when using jQuery?

I am trying to display a message bar during postback. I am using a jQuery script I found online here. Everything works great separately, but when the jQuery is added to the page my server side event is never called.
Here is my button code:
<asp:Button ID="btnGetReport" CssClass="float-left" runat="server"
Text="<%$ Glossary:GetReport %>" OnClick="btnGetReport_Click" />
This is the inline script:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btnGetReport.ClientID%>').click(function (event) {
event.preventDefault();
$('#message_bar').displayMessage({
position: 'fixed',
skin: 'modern',
message: 'We are fetching your report. Please wait...',
});
});
});
</script>
This is the related external .js file:
(function( $ ){
$.fn.displayMessage = function(options) {
// Default configuration properties.
var defaults = {
message : 'Error message',
speed : 'fast',
position : 'fixed', // relative, absolute, fixed
autohide : true
}
var options = $.extend( defaults, options );
$(this).slideUp('fast');
$(this).removeClass().empty();
return this.each(function() {
var sticky = (options.sticky == false) ? 'relative' : 'absolute';
$(this).addClass('messagebar-skin-'+options.skin+'_bar').css('position',options.position).css('background-color',options.background);
$(this).append('<div class="messagebar-skin-'+options.skin+'_inner"><span class="messagebar-skin-'+options.skin+'_text"></span></div>').css('color',options.color);
$(this).find('span').html(options.message);
$(this).slideDown(options.speed ,function(){
var parent = ($(this).attr('id')) ? "#"+$(this).attr('id') : "."+$(this).attr('class');
var close_button = ($(this).find('a').attr('id')) ? "#"+$(this).find('a').attr('id') : "."+$(this).find('a').attr('class');
if(options.autohide == true)
{
$(this).delay(2400).fadeOut('slow');
}
$(parent+">div>"+close_button).bind("click", function (event) {
event.preventDefault();
$(parent+">div>"+close_button).animate({"opacity": "hide"}, function(){
$(parent+">div>span").fadeOut("slow").html("");
$(parent+">div>"+close_button).parent().parent().slideUp(options.speed);
});
});
});
});
};
})( jQuery );
I have also tried calling the function with the OnClientClick property, but neither one seems to work. I looked at other examples where people were having issues with this but none of them seemed to help either.
Any thoughts would be greatly appreciated!
Have you tried something simple like:
OnClientClick="return YourJavaScriptFunction();"
<asp:Button ID="btnGetReport" CssClass="float-left" runat="server"
Text="<%$ Glossary:GetReport %>" OnClick="btnGetReport_Click"
OnClientClick="return YourJavaScriptFunction();" />
and in your JavaScript function return true at the end
function YourJavaScriptFunction () {
// your cool stuff
return true;
}
Edit 1
This line:
OnClientClick="return YourJavaScriptFunction();"
It's the equivalent to:
$('#<%=btnGetReport.ClientID%>').click(function () {
Your script would look like:
<script type="text/javascript">
function YourJavaScriptFunction (){
$('#message_bar').displayMessage({
position: 'fixed',
skin: 'modern',
message: 'We are fetching your report. Please wait...'
});
// this will prevent the postback, equivalent to: event.preventDefault();
return false;
}
</script>
Try this:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btnGetReport.ClientID%>').click(function (event) {
event.preventDefault();
$('#message_bar').displayMessage({
position: 'fixed',
skin: 'modern',
message: 'We are fetching your report. Please wait...',
});
__doPostBack("btnGetReport", "");
});
});
</script>
if using Master Page then try this:
__doPostBack("ctl00$MainContent$btnGetReport", "");

JQuery Dialog() can't open again after close

Following code is a pretty simple and complete JQuery Dialog. Everything works.
Problem is as mentioned at the title in js1.js: (see its comment)
It always try to load the page by calling horsedlgcontainer.load('page2.html'); never hits the else horsedlg.dialog('open'); statement.
Any idea please? Thank you very much!
page1.html ...
<!DOCTYPE html>
<head>
<link href="Site.css" rel="stylesheet" type="text/css" />
<link href="jquery-ui-1.8.21.custom.css" rel="Stylesheet" type="text/css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<script src="js1.js" type="text/javascript"></script>
</head>
<body>
<div id="horse-link">
[<a id="horse-link-show-dialog">Click Me</a>]
</div>
<div id="horse-link-dialog-container"></div>
</body>
page2.html ...
<script src="js2.js" type="text/javascript"></script>
<div id="horse-dialog" title="Horse!">
Q: When is a horse not a horse?<br />
A: It depends, when a white horse is not a horse.<br />
</div>
js1.js ...
$(document).ready(function () {
var horselnk = $('#horse-link'),
horsedlg = $('#horse-dialog'),
horsedlgcontainer = $('#horse-link-dialog-container'),
showdlgbtn = $('#horse-link-show-dialog');
$.ajaxSetup({ cache: false });
showdlgbtn.click(showHorseDialog);
function showHorseDialog() {
if (horsedlg.length==0)
horsedlgcontainer.load('page2.html');
else //to improve performance, open it again, don't load the same page
horsedlg.dialog('open'); //Why never come here?!?
}
});
js2.js ...
$(document).ready(function () {
var horsedlg = $('#horse-dialog'),
horselnk = $('#horse-link');
horsedlg.dialog({
modal: true, autoOpen: true, resizable: false,
height: 500, width: 350, closeOnEscape: true,
show: {effect:'puff',percent:150,duration:250},
hide: {effect:'puff',percent:110,duration:250}
});
});
You're only evaluating horsedlg = $('#horse-dialog') once, and it's before the content is loaded, so its .length property is always zero.
I suspect you'll also run into problems with loading a secondary JS file when you load the dialog content. A single JS file would be cleaner:
$(document).ready(function () {
var options = {
modal: true, autoOpen: true, resizable: false,
height: 500, width: 350, closeOnEscape: true,
show: {effect:'puff',percent:150,duration:250},
hide: {effect:'puff',percent:110,duration:250}
};
var loaded = $.Deferred();
$('#horse-link-show-dialog').on('click', function() {
var state = loaded.state();
if (state === 'resolved') {
$('#horse-dialog').dialog('open');
} else if (state === 'pending') {
// do nothing
} else {
$('#horse-link-dialog-container').load('page2.html')
.fail(loaded.reject);
.done(function() {
$('#horse-dialog').dialog(options);
loaded.resolve();
});
});
}
});
});
This uses a jQuery deferred object to indicate whether the dialog box has finished loading or not.
NB: code untested - jsfiddle isn't good for testing AJAX.
As metnioned by #Alnitak the issue is you are trying to search for #horse-dialog even before the element is available in the dom..in your case it will be available after the page2.html load.
Tweak your code to as below and you can do away with js2.js:
$(document).ready(function () {
var horsedlgOptions = {
modal: true, autoOpen: true, resizable: false,
height: 500, width: 350, closeOnEscape: true,
show: {effect:'puff',percent:150,duration:250},
hide: {effect:'puff',percent:110,duration:250}
};
var horselnk = $('#horse-link'),
horsedlg = $('#horse-dialog'),
horsedlgcontainer = $('#horse-link-dialog-container'),
showdlgbtn = $('#horse-link-show-dialog');
$.ajaxSetup({ cache: false });
showdlgbtn.click(showHorseDialog);
function showHorseDialog() {
if (horsedlg.length==0)
horsedlgcontainer.load('page2.html');
horsedlg = horsedlgcontainer.find("#horse-dialog");
horsedlg.dialog(horsedlgOptions);
else //to improve performance, open it again, don't load the same page
horsedlg.dialog('open');
}
});
The variable horsedlg is locally defined within the first $(document).ready function - so when that code is executed horsedlg.length equals 0 as the DOM element with the id of horse-dialog isnt present on the page.
You cannot change that locally defined variable - so the length always equals 0.
You could do this instead :
function showHorseDialog() {
var horsedlg = $('#horse-dialog');
if (horsedlg.length == 0) {
horsedlgcontainer.load('page2.html');
} else { //to improve performance, open it again, don't load the same page
horsedlg.dialog('open'); //Why never come here?!?
}
}

Categories

Resources