Need Sharepoint like modal pop-up window - c#

I need to show Sharepoint 2010 like pop-up window when clicked on a link in grid view. Once the modal pop-up displayed and user selected the Save button data base should be updated with given values in pop-up. How can I get this. Any Idea.
As of now I am using below code to get it but no idea how to pass the values to Database once clicked on the button in pop-up
Note: As of now I am not adding the gridview code here as I wanted to achieve it first with sample html then wanted to do with grid view.
Java Script
function openDialog() {
var options = {
html: divModalDialogContent, // ID of the HTML tag
// or HTML content to be displayed in modal dialog
width: 600,
height: 300,
title: "My First Modal Dialog",
dialogReturnValueCallback: dialogCallbackMethod, // custom callback function
allowMaximize: true,
showClose: true
};
SP.UI.ModalDialog.showModalDialog(options);
}
//Results displayed if 'OK' or 'Cancel' button is clicked if the html content has 'OK' and 'Cancel' buttons
function onDialogClose(dialogResult, returnValue) {
if (dialogResult == SP.UI.DialogResult.OK) {
alert('Ok!');
}
if (dialogResult == SP.UI.DialogResult.cancel) {
alert('Cancel');
}
}
// Custom callback function after the dialog is closed
function dialogCallbackMethod() {
alert('Callback method of modal dialog!');
}
HTML
<div id="divModalDialogContent">
Hello World!
<input type="button" value="OK"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Ok clicked'); return false;"
class="ms-ButtonHeightWidth" />
<input type="button" value="Cancel"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked'); return false;"
class="ms-ButtonHeightWidth" />
<asp:Button runat="server" ID="btnClicked" Text="Clicked"
onclick="btnClicked_Click" />
<input type="button" value="Open" onclick="openDialog()" />
How can I call db upon clicking 'clicked' button in pop-up. Also I need to send parameters to pop-up
Thanks in advance

If you need ok, cancel or submit button event on popup screens which interacts with Sharepoint list/library or sql database then you need to implement event in your popup. Check below steps:-
your popup page should inherit "Microsoft.SharePoint.WebControls.LayoutsPageBase"
which should have this function:-
protected void EndOperation(int result, string returnValue)
{
string closeModal = String.Format(CultureInfo.InvariantCulture,
"<script type=\"text/javascript\">window.frameElement.commonModalDialogClose
({0}, '{1}');</script>", new object[] { result, returnValue });
this.Page.ClientScript.RegisterStartupScript(base.GetType(),
"CreatePopup", closeModal, false);
}
Implement an event which can be listen on popup action like ok button
public delegate void AddEventHandlerToSPDialogEvent(object sender, PDialogEventHandler e);
public class SPDialogEventHandler : EventArgs
{
public int dialogResult { get; set; } // 0 or 1
public string ReturnValues { get; set; } // can be url or any success/error message
public SPDialogEventHandler(int result, string list)
{
ReturnValues = list;
dialogResult = result;
}
}
Call this event from your button action in popup. for ex:
public event AddEventHandlerToSPDialogEvent ResultOk;
protected void CancelBtn_Click(object sender, EventArgs e)
{
try
{
int dialogResult = 0;
if (this.ResultOk != null)
{// Here dialogResult is 0. that means we have clicked on cancel button
ResultOk(this, new SPDialogEventHandler(dialogResult,"Action Cancelled"));
}
}
catch (Exception ex) { }
}

You can use the Ajax control toolkit, then you should look for the modal popup extender.
Like that you can add .net controls into the overlay/modal overlay and get the values in code behind
for more info see here
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx
SP Popup
Open a modal/pop up form in Sharepoint 2010 with asp.net controls in it

Related

MVC View User Control with JavaScript. How implement popup?

I have a small project which I have a page with a drop-down menu. When the drop-down is selected a user control should popup.
This is an image of what I'm hoping to acomplish:
I have a .ascx file which needs to be loaded. Where would the entry point be added to have this control pop-up?
Here is the implementation. I have started with. This project is not using the code behind and is instead using javascript to implement controls.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AdministratorConsole.Models.TaskActionController.TaskActionViewModel>" %>
<script language="javascript" type="text/javascript">
<!-- Some Funtions -->
</script>
<div class="main_popup_container">
<div class="task-action-header">Action Type: Hyperlink PDFs</div>
<div class="task-configuration-header">Configuration<span id="HyperlinkCopyTestResults" class="one-line-test-results"></span></div>
I have started a method to try to get this .ascx to pop up from the root folder without any luck. What do I need to get this MVC view user control to popup
and execute?
class PageLoad : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Load control from file
Control load = (Control)Page.LoadControl(#"~/PDFHyperlink.ascx");
}
}
I also have a Interface which has and Execute GetName and TestConfiguration to run some test on user inpute and execute my code to hyperlink PDFs.
public bool Execute(TaskActionConfig action, TaskActionAPI.Task t, out string message)
{
message = GetName();
string configMessage = "Test Message";
bool result = TestConfiguration(action, out configMessage);
// Run hyperlinking tool.
HyperlinkingTool(t);
return true;
}
// **************************GetName**************************
public string GetName()
{
string HyperlinkPDFs = "Hyperlink PDFs";
return HyperlinkPDFs;
}
// **************************TestConfiguration**************************
public bool TestConfiguration(TaskActionConfig action, out string message)
{
Dictionary<string, string> parameter = action.Parameters;
bool result = true;
message = "Config Message";
return result;
}
The method GetName() needs to return the same name as the .ascx file. This will register the .ascx file and load it.

Separate button triggers "Please fill out this field"

I am building a web app with C# and asp.net. In the webpage, there is a header with a search bar and a body with a form. When I enter something in the search bar, one of the form fields shows the pop-up, "Please fill out this field".
This field is required, but for the form which has a separate submit button. So what I'm saying is my search button and form are connected but they shouldn't be.
Edit:
Code behind for the search button:
protected void btnOpenModalSearch(object sender, EventArgs e) {
//get information from database to populate the modal box with
PopulateModalBoxGridView();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Properties",
\ "openModal();", true);
}
protected void PopulateModalBoxGridView() {
if (dtSearch == null) return;
//sort the search results in data table
DataView dvSearch = dtSearch.DefaultView;
dvSearch.Sort = SortOrder;
gridSearchResults.DataSource = dvSearch;
gridSearchResults.DataBind();
}
Code behind for the separate form:
protected async void btnCreateNewAsset_Clicked(object objSender, EventArgs evntArgs) {
//create a new asset
//first check for duplicates
if (IsDuplicateAsset()) { return; }
Asset newAsset = new Asset {
//creating asset
};
//post the asset to Team Dynamix
var addAssetUri = new Uri(locationOrigin + webApiBasePath + addAssetPath);
responseMsg = await httpClient.PostAsJsonAsync(addAssetUri, newAsset);
httpResponse = responseMsg.Content.ReadAsStringAsync().Result;
if (!responseMsg.IsSuccessStatusCode) {
Notification.Show(this, "Error. Response content=" + httpResponse, Status.Error);
}
else {
Notification.Show(this, "Successfully Created Asset.", Status.Success);
assetDictionary.Add(serialNumber.Text, serialNumber.Text);
ClearTextFields(frmIndex);
}
}
I found the answer here: HTML 5 required validator triggers on all buttons on the form
To save you the trip, I needed to add formnovalidate="formnovalidate" to my button
<asp:ImageButton ID="BtnSearch" formnovalidate="formnovalidate" data-target="#myModal" ClientIDMode="Static" runat="server" ImageUrl="~/images/search.svg" Text="Search" OnClick="btnOpenModalSearch"></asp:ImageButton>

ASP.NET web app confirmation box - Button.Click

I have an ASP.NET 4.5 web app that contains a form where the user can add some data and I have a button that I want to save the data in the database.
When the user presses this button, the first thing I do is search if there already exists a record for a specific item. If there is, I want to show a confirmation box where I'm letting the user know: "This record already exists. Do you want to update it?". If the user presses YES, I want to do an UPDATE, else I will do an INSERT. The problem is with this damn confirmation box.
What I have so far:
In aspx.cs:
public void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Write("YES");
}
else
{
Response.Write("NO");
}
}
In aspx I have:
<script>
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Record already exists. Do you want to update it?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
and I added a button:
<asp:Button ID="alertBtn" runat="server" OnClientClick = "Confirm()" OnClick="OnConfirm" Text="" style="display:none"/>
If I remove the style and run the app, when I click on this button it works perfectly. The confirmation box shows up, when I click YES it calls a function, when I click NO it calls another function.
But how do I click on this button from code? Nothing works!
I tried with:
1) alertBtn.Click += new EventHandler(this.OnConfirm);// doesn't do anything
2) ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "somekey", "Confirm();", true);// I was only able to run the Confirm() method, but it didn't call the OnConfirm method which is on the server.
3) Following step 2, I tried adding a call from js to c# in the Confirm() method: document.getElementById('<%=alertBtn%>).OnClick // this didn't work either
So I just want to do a Button.Click from code behind in order to trigger the Confirm() method which will open a confirmation box and after I click YES/NO, the OnConfirm method from the server should call the appropriate function based on this YES/NO value. If you have another solution besides the one with using a button, I'm open to new ideas.
Update
To better explain my problem, I added this demo link. I want to achieve the same thing without having to click on a button, just from code.

pop up does not go for post back in asp.net

I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}

Telerik window automatically opens after every page refresh

I am using Telerik RadControls in my project and and have a menu where I have an 'About' button. When I click the 'About' button a window pops up describing the application. The problem is if I refresh the page or navigate to another page then back to the first page the window automatically pops up.
The goal is only have that window pop up when the user clicks the about button.
here is the code I used to get that window:
<!--About Window-->
<telerik:RadWindowManager runat="server" EnableViewState="false" KeepInScreenBounds="true"></telerik:RadWindowManager>
<telerik:RadWindow ID="AboutMenu" Behaviors="Close" Animation="None" runat="server" Width="360px" KeepInScreenBounds="true" Height="360px" Modal="true" VisibleStatusbar="false" Skin="Glow">
<ContentTemplate>
<p style="text-align: center;">Sample Window Information</p>
</ContentTemplate>
</telerik:RadWindow>
Javascript
function OnClientItemClick(sender, eventArgs) {
if (window.args.get_item().get_text() == "About") {
var radwindow = window.$find(window.AboutMenu.ClientID);
window.args.set_cancel(true);
}
}
.cs
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
AboutMenu.VisibleOnPageLoad = true;
}
}
The window works but it loads whenever the page loads and thats where I think the line AboutMenu.VisibleOnPageLoad = true comes into play and is causing the error but when I take out that line it won't display at all.
Instead of using VisibleOnPageLoad try using the following code to open the window on itemclick.
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
string script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
}
}
Or, just use the OnCLientItemClicking event of the menu to open the RadWindow and cancel the postback. But you will need to fix you JS code, because the arguements are in the context of the current function. ALso, the reference to RW may break unless you have made your own array of ClientIDs.
function OnClientItemClicking(sender, eventArgs) {
if (eventArgs.get_item().get_text() == "About") {
var radwindow = window.$find(<%=AboutMenu.ClientID%>);
radwindow.show();
eventArgs.set_cancel(true);
}
}

Categories

Resources