Showing jQuery Modal on form data sucessfully submited to database - c#

I am facing a problem with jquery modal Dialog box. I want the modal box to show only when my data is successful saved to database. I am using c# and asp.net, and on backend i am using Sql server 2008 R2. Currently my data is successfully entering and i am showing "the data is successfully saved on a label" after clicking on a button , but i want to show a modal box only when i click the button and my data is saved .
I have created this script
$("#Btndiag").click(function () { $("#myModal").modal(); });
and on content page body i have written this
<asp:Button ID="Btndiag" runat="server" Text="show dialog" onclick="Btndiag_Click1" />
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Settings</h3>
</div>
<div class="modal-body">
<p>Here settings can be configured...</p>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>

To achieve what you want, you have to process the data in the back end, and then have the ASP.NET Framework execute a script for you.
To accomplish this, you use ClientScriptManager.RegisterClientScriptBlock during full page postbacks, or ScriptManager.RegisterClientScriptBlock if the controls are inside of an UpdatePanel.
C# code:
protected void Btndiag_Click1(object sender, EventArgs e)
{
// process database
// verify results
if (success)
{
ClientScriptManager.RegisterClientScriptBlock(this, "Btndiag_Click1", "$('#myModal').modal();", true);
}
}
Remember that if the button and the modal div are inside of an UpdatePanel, replace ClientScriptManager.RegisterClientScriptBlock with ScriptManager.RegisterClientScriptBlock.
Finally, just as a last informational note...your script ($("#Btndiag").click(...)) will not work because ASP.NET changes element Ids when rendered as HTML.
You'd have to work it in the following manner:
$("#<%= Btndiag.ClientID %>").click(function () { $("#myModal").modal(); });
Please note that you do not need to do anything with the button's click event. You want the framework to automatically run your scrip after the postback.

Related

Create a customized alert box in c# asp.net

I want to create a alert box with asp controls, is it possible?
For example, a simple script alert would be like,
Response.Write("<script>alert('Alert Box');</script>");
On the alert box there are default buttons "Ok" and "Cancel" with the text "Alert Box"
Now all i want to do is call a function written in the respective Demo.aspx.cs page on the click of Ok button of alert.
Or
Is it possible to place a asp:Button control in that alert box to call that function?
Thanks if any of you could help! :)
You can't use asp:Button in JavaScript alert, The best way to make an alert or modal dialog box in asp.net is to create your own and make it hidden or in-active in master page and call it when you need it.
You can get a ready made modal or alert in GetBootstrap
Update:
Here some Idea how to use bootstrap modal.
This is how I use GetBootstrap Modal for asp.net webforms, you can use it if you want.
The following code is use to create a customize alert or modal box with proper asp.net button controls that you can use in back-end. "you can place this in master page to prevent repetitive"
<asp:Panel ID="pnlAlertBox" runat="server" style="position:absolute;top:0;> //You can make is visible or hidden -- you need to customize the style of panel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">This is customize alertbox</h4>
</div>
<div class="modal-body">
This is the messages...
</div>
<div class="modal-footer">
<asp:Button ID="btnCancel" runat="server" CssClass="btn btn-default" Text="Cancel" />
<asp:Button ID="btnOk" runat="server" CssClass="btn btn-primary" Text="Ok" />
</div>
</div>
</div>
</asp:Panel>
But of course you need to include the getboostrap .js and .css files in master page to show the design.
Place this in header:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
Place this after form:
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
This is a fixed version of Abrar Jahin's answer. Calling e.preventDefault() prevents the default action being taken, which is to submit the form.
The following displays the alert on click, and then submits the form: -
$("#alert_button").click( function(e)
{
alert('This is a custom alert box', 'Alert Dialog');
});
EDIT:
If you want to call a specific function in your webpage, you have a few options: -
A PageMethod or HttpHandler
in your client-side code, call the ASP.NET-generated __doPostback function, and pass parameters indicating what to do to your server-side code
without redirect page alert code
ScriptManager.RegisterStartupScript(this, this.GetType(), "showalert", "alert('Demo');", true);
with redirect page
ScriptManager.RegisterStartupScript(this, this.GetType(), "err_msg", "alert('Demo');window.location='Demo.aspx';", true);
You can use javascript inside OnClientClick event handler for the button
<asp:Button ID="Button1" runat="server" Text="Delete User"
OnClientClick="return confirm('Are you sure you want to delete this user?');" />

Showing CustomValidator in modal dialog

I have my ValidationSummary showing in a modal dialog. That is working fine.
However my code-behind performs some database lookups and adds messages with a CustomValidator to my ValidationSummary.
This worked fine before I started showing my ValidationSummary in the dialog. But now when the CustomValidator is invalid it doesn't show in the ValidationSummary dialog.
The dialog comes up when other fields are invalid, but not for the CustomValidator messages from code-behind.
Here's the code that shows the dialog when the page isn't valid:
<script type="text/javascript">
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
$("#modal_validationSummary").modal('show');
return false;
}
return true;
}
</script>
Validation Summary code:
<div class="modal modal-danger" id="modal_validationSummary" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Invalid Login</h4>
</div>
<div class="modal-body clearfix">
<asp:ValidationSummary ID="LoginValidationSummary" runat="server"
ValidationGroup="LoginGroup" HeaderText="<div class='validationheader'>Please address the issues below</div>"
CssClass="validationsummary" DisplayMode="BulletList"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-clean" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My code-behind that adds the CustomValidator:
CustomValidator cv = new CustomValidator();
cv.IsValid = false;
cv.ErrorMessage = "Login not found. Please try again.";
cv.ValidationGroup = "LoginGroup";
this.Page.Validators.Add(cv);
Thanks for any help!
So the sequence of events is: you post back, the validator is added, the page renders, and the Validation Summary doesn't show the error?
At what point is the validation summary displayed? If it's before your initial postback, then your validation message can't appear because validation is preventing you from posting back, and the validation doesn't happen until after postback.
There might also be an issue with the CustomValidator not being added to the Controls collection, but I'm not sure about that.
ETA: a little research reinforced my belief that the pop-up ValidationSummary window only works with client-side validation. Yours is server-side. You can make a CustomValidator function as a client-side validator while still performing work on the server, but you need to:
Define a client-side validation function;
Perform an AJAX call within that client-side function;
Declare your CustomValidator in the markup. (You could still add it dynamically, but it would be on your initial render, and you'd have to add it to the Controls collection.)
That's the very condensed version of it, anyway.

onClick bind to Url.ActionLink only works first time

So I have a Url.ActionLink, that when clicked, I want to load a partial view into a modal. This works the first time, but the second time it redirects the browser to the partial view instead of loading it into a modal, and the modal() call has an error saying that it is undefined.
The html for the div is:
<div class="modal fade" id="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="modalBody"></div>
</div>
</div>
</div>
The code for the binding/loading so far is:
$(".actionLink").on("click", function (e) {
e.preventDefault();
$("#modalBody").load(e.target.href);
$("#modal").modal('show');
return false;
});
The error that I'm getting before the redirect is on the $("#modalBody").load(e.target.href); and the error is "Uncaught TypeError: undefined is not a function." It works the first time a link is clicked, so I don't know why it would be undefined the second time.
The .on() type of binding works only with the elements which was created before the script has been initialised.
So if you load some content dynamically in the on click function, the on() binding won't work for that content.
One solution could be if you bind the click event to the container element, where you load the new content, something like this:
$("#container").on("click", ".actionLink", function(e) { ... });
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()"
jQuery .on() doc

Add ASP.NET Element to JQuery Dialog dynamically

I am placing some ASP.NET html elements(that upload a file) inside a JQuery Dialog.
My Problem: When I click the button to upload the file, nothing happens. I create the query dialog dynamically AFTER the page has loaded. My solution is to place the HTML/ASP elements(for uploading a file) in a div at the bottom of the body of the page & set its display to none.
Then upon opening the dialog, I move the HTML/ASP elements into the JQuery dialog. But my problem is that when I click my ASP.NET button to upload the file from within the dialog, nothing happens?
Note if I click the button whilst its outside the JQuery dialog is sucessfully uploads the file.
Whats going wrong & how do I fix this? Is there an easier way to add ASP.NET code to a JQuery dialog AFTER the page has loaded?
This sits in the body
<div id="test">
<input class="ui-button ui-widget ui-state-default ui-corner-all
ui-button-text-only"
style="display: inline-block;" id="fileUpload" type="file" Runat="server"
NAME="fileUpload"/>
<asp:button id="btnSave" OnClick="bt1Clicked" style="display: inline;"
class="ui-button ui-widget ui-state-default ui-corner-all
ui-button-text-only"
runat="server" Text="Upload File" ></asp:button>
<asp:label id="lblMessage" runat="server" style="height:20px;width:390px;"
</asp:label>
</div>
Then on dialog open I grab the above HTML & move it into the dialog:
$(this.dialog).dialog('open' function()
{
var e = $("#test");
$(body).remove(e);
$(this).append(e);
});
jQuery UI dialog creates the dialog elements at the very end of the document, right before the closing </body> element. So when you open your dialog and move your content div#test into the dialog, it is outside the <form> and does not work anymore with asp.net which requires it.
Try to create your dialog and move it back inside the <form> element:
$("#myDialog").dialog({
...
}).parent().appendTo($("form"));

ASP.Net Submit Button Not Executing Inside jQueryUI Dialog-Content Loaded From Another Page

I am trying to add a few functions to a ASP.NET page using jQuery UI's dialog. I am attempting to display 3 separate dialogs which allow a user to add or edit a contact's address, phone, or email information.
I have a UserView page which contains the jQuery, a GridView, and the DIVs I load the controls into. I am using jQuery's .load(url + '#DIV', function... capability to load the 3 boxes from a second page called UserFunctions.
The boxes all load and are populated correctly with data, however, the save button does not submit the changes skipping the button's click command. Is there a way to do this? Can I manually call postback from the jQuery dialog? I would like to stay away from IFrames if at all possible.
UserView jQuery Code
$('#addPhone').load('/Administration/UserFunctions.aspx?Mode=edit&Record=1' + ' #PhoneAdd', function () {
$(this).dialog({
modal: true,
autoOpen: false,
draggable: true,
width: 600,
open: function (type, data) {
$(this).parent().appendTo("form:first");
},
buttons: {
"Close": function () { $(this).dialog("close"); }
}
});
});
UserView and Show Dialog Button
Add Phone<br /><br />
<div id="addPhone">
</div>
UserFunction DIV that is loaded
<div id="PhoneAdd">
<p><span class="Type">Phone Type
<asp:DropDownList ID="ddPhoneType" runat="server" Width="205px"
DataSourceID="odsPhoneType" DataTextField="PhoneName"
DataValueField="PhoneTypeID">
</asp:DropDownList>
<asp:ObjectDataSource ID="odsPhoneType">
</asp:ObjectDataSource>
</span></p>
<p><span class="Number">Number
<asp:TextBox ID="ttPhoneNumber" runat="server" Width="100" ></asp:TextBox></span>
<span class="Extension">Extension
<asp:TextBox ID="ttPhoneExtension" runat="server" Width="50" ></asp:TextBox></span></p>
<p><span class="PhoneSubmit"><asp:Button ID="btnPhoneSubmit" runat="server"
Text="Save" onclick="btnPhoneSubmit_Click" />
</span></p></div>
UserFunction Button Click Event (which does not fire)
protected void btnPhoneSubmit_Click(object sender, EventArgs e)
{
if (qString == "insert")
{ //insert to database. Code removed to save room. }
if (qString == "edit")
{ //update database}
}
The Code Behind above never runs (tested by attempted to debug the if statement).
Thank you in advance for your help. I appreciate it very much.
The problem here is, since you modal box are ajax requests they are not posting back to their respective pages but instead posting back to the parent page (UserView).
You could possibly handle this by putting a form in your modal and have it post to another page and handle the form inputs there.
<form action="/User/PostPhone.aspx" method="post">
//form elements in here
</form>
Then your PostPhone.aspx code behind will have do something like:
if (IsPostBack)
{
var phoneNumber = Request["phonenumber"];
//save phone number
}

Categories