Using SimpleModal and ASP.NET MVC - asp.net

I am using Simple Modal with asp.net MVC. I have set it up using the OSX demo, which loads a view into the dialog.
The javascript I am using is:
jQuery(function($) {
$("input.ema, a.ema").click(function(e) {
e.preventDefault();
$("#osx-modal-content").modal({
appendTo: 'form',
overlayId: 'osx-overlay',
containerId: 'osx-container',
closeHTML: '<div class="close">X</div>',
minHeight: 80,
opacity: 65,
position: ['0', ],
overlayClose: true,
onOpen: OSX.open,
onClose: OSX.close,
onShow: OSX.show
});
});
var OSX = {
container: null,
open: function(d) {
var self = this;
$.ajax({
url: "/Message/UserMessage/",
type: 'GET',
dataType: 'html', // <-- to expect an html response
success: doSubmitSuccess
});
function doSubmitSuccess(result) {
$('div#osx-modal-data').html(result);
}
self.container = d.container[0];
d.overlay.fadeIn('slow', function() {
$("#osx-modal-content", self.container).show();
$('div#osx-modal-title').html("Send Email");
var title = $("#osx-modal-title", self.container);
title.show();
d.container.slideDown('slow', function() {
setTimeout(function() {
var h = $("#osx-modal-data", self.container).height() +
title.height() +
20; // padding
d.container.animate({
height: h
}, 200, function() {
$("div.close", self.container).show();
$("#osx-modal-data", self.container).show();
});
}, 300);
});
})
},
close: function(d) {
var self = this;
d.container.animate({
top: "-" + (d.container.height() + 20)
}, 500, function() {
self.close(); // or $.modal.close();
});
},
show: function(d) {
var self = this;
$("#txtEmail", self.container).hide();
});
}
};
});
On the show function I am trying to hide the txtEmail box, but it doesnt seem to be able to find it.
The HTML which is going into the dialog is
<%# Page Language="VB" Inherits="System.Web.Mvc.ViewPage" %>
<!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 runat="server">
<title>CreateMessage</title>
</head>
<body>
<div>
<p>
<input id="txtEmail" type="text" style="width: 90%" /></p>
<p>
<textarea id="TextArea1" cols="20" rows="5"></textarea></p>
<p>
<input id="submitmsg" type="submit" value="Send" /></p>
</div>
</body>
</html>
Can anyone help me out on this?
Thanks,

I believe that the AJAX call hasn't completed by the time the show method is invoked and thus the element doesn't exist at the time that you are going to hide it. You should probably move all of the code following the ajax call in the open handler into the ajax callback, along with the code to hide the txtEmail element.
var OSX = {
container: null,
open: function(d) {
var self = this;
$.ajax({
url: "/Message/UserMessage/",
type: 'GET',
dataType: 'html', // <-- to expect an html response
success: function(html) {
$('div#osx-modal-data').html(result)
.find("#txtEmail")
.hide();
...rest of code to display the dialog...
}
});

Related

Auto Close JQuery UI Dialog

All,
I am trying to set a timeout on my JQuery UI Dialog but have not been able to get it to work. I read several SO posts and the docs on setTimeout() but apparently I am not implementing it correctly.
Below, is the syntax that I am using to set up my timeout, along with the dialog HTML.
Thanks
$.ajax({
type: "POST",
url: '/Dashboard/BackgroundCheck',
data: queryStr,
datatype: 'json',
success: function (data) {
if (data == true) {
$("#dialog-message").attr('title', 'Success!');
$(".js-dialog-content").html('Background Check status saved.');
$("#dialog-message").fadeIn('slow');
$("#dialog-message").dialog({
modal: true,
buttons: {
Ok: function () {
setTimeout(function() {
$(this).dialog("close");
},5000);
}
}
});
}
}
});
}
});
Dialog Box
<div id="dialog-message" title="" style="display:none">
<p>
<span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;"></span>
<span class="js-dialog-content"></span>
</p>
</div>
You should define your dialog parameters and you can use autoOpen or open it manually. please attention to this sample:
$('#dialog-message').dialog({
autoOpen: false,
resizable: false,
show: 'fade',
hide: 'fade',
height: 240,
modal: true,
dialogClass: "alert",
close: function (event, ui) { /*do somthing you want*/ },
open: function (event, ui) { setTimeout(function () { $('#dialog-message').dialog("close"); }, 2000) }
}).dialog("open");
As you can see i set the timeout in function related to open parameter.
Good Luck.

What is the reason behind popup opening only first time

I have a strange problem and i m not able to understand why it is happening.
I called a page - Remarks(say) by jquery ajax on row click of grid viw. Then i binded that page (coming in response) into a div - dvRemarks(say). This div is opening in a popup.
Pop-up window is only opening first time, which is working fine. But when i click second time, data is coming in response, But this time popup is not opening. Problem is with popup only but i don't understand why it is ?
When i again refresh the page, it again opens up Ist time only.
Below is jquery :-
jQuery(function() {
// Remarks
jQuery('#<%=dvRemarks1.ClientID %>').dialog({
autoOpen: false,
width: 600,
modal: true
});
// Remarks Link
jQuery('#lnkDialog').click(function() {
jQuery('#<%=dvRemarks1.ClientID %>').dialog('open');
return false;
});
});
Below is the function which i am calling on click :-
function Call_Ajax(id)
{
var d = new Date();
var n = d.getMilliseconds();
var parameters="id=" + id;
$.ajax({
type: "POST",
url: "Remark.aspx",
data: {id:id, n:n},
success: function(response) {
$('#<%=dvRemarks.ClientID %>').html(response);
$("#lnkDialog").click();
},
error: function() {
alert('Some problem has been occured.');
}
});
}
And below is the div - dvRemarks in which i am binding response
<div id="dvRemarks1" runat="server" style="display: none;" title="Enter Remarks">
<div id="dvRemarks" runat="server">
</div>
</div>
Thanks.
Not sure on this but give a try to below one.
jQuery(function() {
// Remarks
jQuery('#<%=dvRemarks1.ClientID %>').dialog({
autoOpen: false,
width: 600,
modal: true, //Calling destroy on close function might help
close: function() {
$(this).dialog("destroy");
}
});
// Remarks Link
jQuery('#lnkDialog').click(function() {
jQuery('#<%=dvRemarks1.ClientID %>').dialog('open');
return false;
});
});
give a try changing ajax call to
function Call_Ajax(id)
{
var d = new Date();
var n = d.getMilliseconds();
var parameters="id=" + id;
$.ajax({
type: "POST",
url: "Remark.aspx",
data: {id:id, n:n},
success: function(response) {
$('#<%=dvRemarks.ClientID %>').empty().html(response); //empty function may be of some help here
$("#lnkDialog").click();
},
error: function() {
alert('Some problem has been occured.');
}
});
}

Partial view render on button click

I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/
The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.
Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....

asp.net submit button close Jquery Ajax

I am working on an asp.net page where I have used JQuery UI dialogue. This dialogue has a submit button. When I click the submit button dialogue closes. I want to call a Webmethod on it. If method returns ture, then I want to close it otherwise I want to keep it open with error message shown.
[Edited]
<script>
jQuery(function () {
var dlg = jQuery("#dialog").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10,
beforeClose: function () {
$.ajax({
url: "Default.aspx/GetResult",
success: function (response) {
if (response == true) {
("#dialog").close()
}
else {
alert('asdasdds');
}
}
});
return false; //this will stop dialog box to close
}
});
dlg.parent().appendTo(jQuery("form:first"));
});
</script>
<div id="Result">
Click here for the time.</div>
<div id="dialog" style="text-align: left; display: none;">
<asp:Button ID="btnButton" runat="server" Text="Button" OnClick="btnButton_Click" />
</div>
how to do it. Please suggest.
Regards,
Asif Hameed
You can call webmethod using ajax and then act on it conditionally based on the response. Let your webmethod just return true/false and then you can check this value on the client side.
Execute this code on submit button click and do not close the dialog. Let the success handler decide whether to close it or no.
$.ajax({
url: "urlOfTheService.asmx/methodName",
success: function(response){
if(response == true){
//Code to close the dialog
}
else{
//Show the error message
}
}
});
ajax() reference: http://api.jquery.com/jQuery.ajax/
Update:
Use open event of dialog box to attach the submit handler to form and execute the above code.
jQuery(function () {
var dlg = jQuery("#dialog").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10,
open: function(){
$(this).find('form')
.unbind('submit')
.submit(function(){
var $form = $(this);
$.ajax({
url: "urlOfTheService.asmx/methodName",
success: function(response){
if(response == true){
//Submit the form
$form.unbind('submit')[0].submit();
}
else{
//Show the error message
}
}
});
return false;
});
}
});
dlg.parent().appendTo(jQuery("form:first"));
});

jQuery UI Dialog + Validate

I'm having trouble in validating a jQuery UI dialog using Jquery Validate upon clicking Save.
Here's my code to create Jquery dialog. It loads the dialog from a target a href URL:
$(document).ready(dialogForms);
function dialogForms() {
$('a.dialog-form').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.find('#return').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {submitFormWithAjax($(this).find('form'));},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
width: 'auto'
});
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
beforeSend: function(data) {
//alert("beforesend");
form.validate();
},
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'text',
error: function(data) {
alert(data);
$('#result').html(data);
},
success: function(data) {
//alert("success");
$('#result').html(data);
setTimeout("reloadPage()", 500);
}
});
return false;
}
The beforeSend is called, but it doesn't seem to call the validate method, which is located on the parent page from which Dialog is called.
$(document).ready(function() {
$("#event_form").validate({
rules: {
Name: {
required: true
},
Category: {
required: true
}
},
messages: {
Name: "Please enter an event name",
Category: "Please choose a category"
},
submitHandler: function(form) {
alert("validated");
// $('#loading_1').show();
// $('#proceed_c').hide();
// $(form).ajaxSubmit();
// //form.submit();
},
errorPlacement: function(error, element) {
error.appendTo(element.next(".status"));
}
});
}
Is the problem with the beforeSend within submitFormWithAjax function, the location of $("#event_form").validate or the submitHandler: function(form) within it? Any help will be greatly appreciated.
When you initialize the jQueryUI dialog, it modifies the DOM, the whole dialog is taken out of it's location in the page and inserted right before the </body> tag. You can see this with Firebug. This causes a problem for Validate, because now the form is empty. To solve this, on the dialog's open event, append it to the form. It sounds really wacky, but trust me, it works :)
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {submitFormWithAjax($(this).find('form'));},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
open: function(){
$(this).parent().appendTo($('#event_form'));
},
width: 'auto'
});
Edit:
<form id='event_form'>
<div id="dialog" title="DialogTitle">
</div>
</form>
Took a slightly different approach to this. I needed to reuse my modal form so I append it once jquery "creates" the modal:
$("#mdl_Subject").dialog({
autoOpen: false,
show: "drop",
hide: "drop",
modal: true,
create: function () {
$(this).parent().appendTo($('#aspnetForm'));
}
});

Resources