Wednesday, November 5, 2014

passing argument between the modal popup and the page in sharepoint




http://sharepoint.stackexchange.com/questions/56963/how-can-i-send-data-to-a-modal-popup-without-using-a-jquery-string

as a bit of background I am new to Sharepoint development, as well as web programming in general. I've done asp.net programming in the past, but not much javascrip/ajax/jquery. From the (tons...) of research I've done on this so far, it looks like I'll need to do something like an AJAX post with my data encoded into JSON. I just can't figure out how to link up the POST to my modal popup so I can receive the data, deserialize it, and use the data.
My requirement is relatively simple: I need to grab data from a gridview and populate the listview in my popup with those values. The reason I don't want to use the ? parameters in the url is because our users can select hundreds of values if they want to, and I don't want there to be an exception because the url is too long (correct me if I'm wrong).
Here's my attempt, right now I'm just throwing dummy strings at the ajax post so I can keep it as simple as possible.
Here's my javascript associated with my custom web part:
<script language="javascript" type="text/javascript">
function OpenDialog(URL) {
    var NewPopUp = SP.UI.$create_DialogOptions();
    NewPopUp.url = URL;
    NewPopUp.width = 700;
    NewPopUp.height = 350;
    SP.UI.ModalDialog.showModalDialog(NewPopUp);

    var myjson = { root: { id: ['000001']} }
    var string = "this is a string";

}
Here's a function to basically send and ajax post to itself, just to test functionality. I can't grab this data though, or see the alert, so something is messed up here.
<script language="javascript" type="text/javascript">
function PostIt() {
    $.ajax({
        type: "POST",
        url: "/_layouts/folder/myPage.aspx",
        data: string,
        timeout: 1000000,
        success: function (data) {
            alert("success");
        }

    });
}
Here's the code I was trying to use to grab the posted data (on button click) but it doesn't seem to do anything. I originally had this in my page_load, but then the modal wouldn't even show up. I'm not exactly sure on the control flow of ajax POSTing, so I could see why a button click would not be able to grab the data, I'm just not sure what else to do.
protected void Button2_Click(object sender, EventArgs e)
    {

        StreamReader reader = new StreamReader(Page.Request.InputStream);

        string test;
        test = reader.ReadToEnd();
        JavaScriptSerializer jss = new JavaScriptSerializer();
        Label1.Text = jss.Deserialize<String>(test);
    }
So I can open my dialogue, press buttons on the dialog, etc, but the button doesn't grab the data I'm trying to send. And Ideally, it would be sent when the window first pops up instead of on button click.
Thanks in advance for the help, I know this is a lot of code for a simple question, I just don't know where I'm going wrong.

I am not sure how you are trying to link up the above code, but will try best to answer. You can just pass a javascript object to the modal dialog instead of query string.
Launching modal dialog with args option:
var options = SP.UI.$create_DialogOptions();
options.width = 700; options.height = 600; 
options.args = { 'SomeVarName': 'somevalue' }
options.url = "http://yoursite/_layouts/yourpage.aspx"
SP.UI.ModalDialog.showModalDialog(options);

And in dialog page access your data like below.
SP.UI.ModalDialog.get_childDialog().get_args()['SomeVarName'];
The second part of your question, if you would like to post some data to a page. You can do something like this SomePage.aspx: $.ajax({ type: "POST", url : "http://yoursite/../somepage.aspx/MethodThatAcceptsData" data : jsonString, contentType : "application/json; charset=utf-8", dataType: "json" success: function(msg) { });
In c# (codebehind)
[WebMethod]
[ScriptMethod(UseHttpGet=false, ResponseFormat = ResponseFormat.Json)]
public static bool MethodThatAcceptsData(Class objectToDesearlizeTo)
{
 //Your code here
 return true;
}

How can I send data to a modal popup without using a jquery string?

as a bit of background I am new to Sharepoint development, as well as web programming in general. I've done asp.net programming in the past, but not much javascrip/ajax/jquery. From the (tons...) of research I've done on this so far, it looks like I'll need to do something like an AJAX post with my data encoded into JSON. I just can't figure out how to link up the POST to my modal popup so I can receive the data, deserialize it, and use the data.
My requirement is relatively simple: I need to grab data from a gridview and populate the listview in my popup with those values. The reason I don't want to use the ? parameters in the url is because our users can select hundreds of values if they want to, and I don't want there to be an exception because the url is too long (correct me if I'm wrong).
Here's my attempt, right now I'm just throwing dummy strings at the ajax post so I can keep it as simple as possible.
Here's my javascript associated with my custom web part:
<script language="javascript" type="text/javascript">
function OpenDialog(URL) {
    var NewPopUp = SP.UI.$create_DialogOptions();
    NewPopUp.url = URL;
    NewPopUp.width = 700;
    NewPopUp.height = 350;
    SP.UI.ModalDialog.showModalDialog(NewPopUp);

    var myjson = { root: { id: ['000001']} }
    var string = "this is a string";

}
Here's a function to basically send and ajax post to itself, just to test functionality.
 I can't grab this data though, or see the alert, so something is messed up here.
<script language="javascript" type="text/javascript">
function PostIt() {
    $.ajax({
        type: "POST",
        url: "/_layouts/folder/myPage.aspx",
        data: string,
        timeout: 1000000,
        success: function (data) {
            alert("success");
        }

    });
}
Here's the code I was trying to use to grab the posted data (on button click) but it doesn't seem to do anything. I originally had this in my page_load, but then the modal wouldn't even show up. I'm not exactly sure on the control flow of ajax POSTing, so I could see why a button click would not be able to grab the data, I'm just not sure what else to do.
protected void Button2_Click(object sender, EventArgs e)
    {

        StreamReader reader = new StreamReader(Page.Request.InputStream);

        string test;
        test = reader.ReadToEnd();
        JavaScriptSerializer jss = new JavaScriptSerializer();
        Label1.Text = jss.Deserialize<String>(test);
    }
So I can open my dialogue, press buttons on the dialog, etc, but the button doesn't grab the data I'm trying to send. And Ideally, it would be sent when the window first pops up instead of on button click.
Thanks in advance for the help, I know this is a lot of code for a simple question, I just don't know where I'm going wrong.
shareimprove this question
I am not sure how you are trying to link up the above code, but will try best to answer. You can just pass a javascript object to the modal dialog instead of query string.
Launching modal dialog with args option:
var options = SP.UI.$create_DialogOptions();
options.width = 700; options.height = 600; 
options.args = { 'SomeVarName': 'somevalue' }
options.url = "http://yoursite/_layouts/yourpage.aspx"
SP.UI.ModalDialog.showModalDialog(options);

And in dialog page access your data like below.
SP.UI.ModalDialog.get_childDialog().get_args()['SomeVarName'];
The second part of your question, if you would like to post some data to a page. You can do something like this SomePage.aspx: $.ajax({ type: "POST", url : "http://yoursite/../somepage.aspx/MethodThatAcceptsData" data : jsonString, contentType : "application/json; charset=utf-8", dataType: "json" success: function(msg) { });
In c# (codebehind)
[WebMethod]
[ScriptMethod(UseHttpGet=false, ResponseFormat = ResponseFormat.Json)]
public static bool MethodThatAcceptsData(Class objectToDesearlizeTo)
{
 //Your code here
 return true;
}
  

Your variable string is scoped to a function, and so you can not reach it outside the function.
 Also the modal window will be using an iframe, so reaching the variable like you try should
 not work.
Instead you could either pass your data as a query string, like this:
OpenPopUpPage('/?string=this%20is%20a%20string');
You can then reach this data through window.location.search.
Another option is to use the global object (window) and add that to the parent of the modal.
window.hack = 'this is a string';
// This will work with any object
window.hackObj = { my: { string: 'this is a string' } };
Inside the modal you can then reach this with window.parent.hack.
var data = window.parent.hack;
$.post('/_layouts/StudentCohorts/CohortCreation.aspx', {data: data}, function() {
    console.log('Success');
});
Note that this will not work if you break Same Origin Policy.

How to pass values from SP UI Modal Dialog 

back to the server side code upon button click event

I have a click event on a button that opens a sp ui modal dialog page. and returns a specific
 value from a text area on that page. I was able to open the page in the modal dialog and
 able to return the values from the text area back to the parent page, but my issue is I was
 not able to pass these values back to the code behind. I tried to use the hidden field. It seems
 to be working but the problem is upon first click event of the button, the values are not
 returned and when I tried to debug it, the whole event is being executed first so the
 values are always empty on first click.
Is there another way that I can pass the values back to the code behind?
Here is the code behind of the button:

function CloseCallback(strReturnValue, comment) {

    if (strReturnValue == 1) // Perform action on Ok.
    {

        var hiddenResult =   $("[id$='ctl00_PlaceHolderMain_HiddenField1']").val(strReturnValue);
        var hiddenComment = $("[id$='ctl00_PlaceHolderMain_HiddenField2']").val(comment);

     }
}
Thank you very much for the help in advance.

Passing parameters into a Modal Dialog Window

Opening a web page in a Modal Dialog Window we can pass parameters to it through the args property of dialog options. A typical JavaScript might look like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function OpenDialog() {
  var opt = {
    url     : 'somePage.aspx',
    autoSize: true,
    /* additional parameters */
    args: { arg1: 'The second argument is ', arg2: 12345 },
    dialogReturnValueCallback:
      function (res, retVal) {
        if (res === SP.UI.DialogResult.OK) { /* do something */ }
        else { /* do something else */ }
      }
  };
  SP.UI.ModalDialog.showModalDialog(opt);
}
Now let’s take a look how these parameters can be accessed from within the Parent-page and the page opened in the dialog.

Accessing the arguments from within the page opened in the dialog

In general case, when opening a SharePoint-based page, the passed arguments could be reached using a script similar to the following:
1
2
3
4
function DoSomethingWithArgs() {
  var passedArgs = SP.UI.ModalDialog.get_childDialog().get_args(); /* get access to the passed parameters */
  alert(passedArgs.arg1 + passedArgs.arg2);
}
The key method here is SP.UI.ModalDialog.get_childDialog, which allows to get the current dialog, or, to be more precise, the current SP.UI.Dialog object. The retrieved object, in turn, exposes the get_args method to access the passed parameters.
A possible use of the DoSomethingWithArgs function from the sample above is
1
2
3
4
<a href="#"
  onclick="ExecuteOrDelayUntilScriptLoaded(DoSomethingWithArgs, 'sp.ui.dialog.js'); return false;">
Show me the passed arguments
</a>
In case the web page opened in the dialog knows nothing about SharePoint and doesn’t include appropriateSharePoint JavaScript files, use the following version of the code:
1
2
3
4
function DoSomethingWithArgs() {
  var passedArgs = window.frameElement.dialogArgs; /* get access to the passed parameters */
  alert(passedArgs.arg1 + passedArgs.arg2);
}
Where the dialogArgs as a property of the window.frameElement object is provided by SP Dialog framework and returns the passed arguments.
Assuming the SharePoint‘s ExecuteOrDelayUntilScriptLoaded function isn’t available as well, the possible use of the DoSomethingWithArgs is quite straightforward:
1
2
3
<a href="#" onclick="DoSomethingWithArgs(); return false;">
Show me the passed arguments
</a>
All other conditions being equal, I recommend the approach with the window.frameElement object as it works always and doesn’t require the page in the dialog to be bound to SharePoint somehow.

Accessing the passed arguments from within the Parent-page

The Parent-page is a place where we define parameters and pass them to the dialog. So, the most direct way is to store the required values into some variable(s) to access them later. Another way is to rely on Dialog framework and use the code already mentioned in the previous section, namely
1
2
3
//...
var passedArgs = SP.UI.ModalDialog.get_childDialog().get_args();
//...
The more interesting case, however, is to access the passed arguments inside thedialogReturnValueCallback function. The listing below contains an example of one of suchdialogReturnValueCallback definitions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function OpenDialog() {
  var opt = {
    url     : 'somePage.aspx',
    autoSize: true,
    /* additional parameters */
    args: { arg1: 'The second argument is ', arg2: 12345 },
    dialogReturnValueCallback:
      function (res, retVal) {
        if (res === SP.UI.DialogResult.OK) {
          var passedArgs = this.get_args(); /* get access to the passed parameters */
          alert(passedArgs.arg1 + passedArgs.arg2);
        }
      }
  };
  SP.UI.ModalDialog.showModalDialog(opt);
}
The dialogReturnValueCallback function will be called in the context of the SP.UI.Dialog object associated with the current Modal Dialog Window. Therefore, inside the function the passed arguments can be accessed using this-keyword.
A possible use of the OpenDialog is shown below:
1
2
3
4
<a href="#"
  onclick="ExecuteOrDelayUntilScriptLoaded(OpenDialog, 'sp.ui.dialog.js'); return false;">
Open Modal Dialog Window
</a>
ps There is a quite detailed article about dealing with Dialogs in SharePoint 2010. So, read to learn more about Dialog framework.


showModalDialog: send and return values

Author: satz | Date: March 16, 2012
This article shows how to send and return values using the modal dialog. We learn how to send an array object information to the modal dialog and return an Object back to the parent window.

Method to show Modal Dialog

function showModal()
 {
 // Object to be sent the modal dialog
 var obj = [{"name":"tutorials2learn","url":"http://www.tutorials2learn.com"}, {"name":"sampleName","url":"http://www.sampleURL.com"}, {"name":"sampleName2","url":"http://www.sampleURL2.com"},{"name":"sampleName3","url":"http://www.sampleURL3.com"}]
var dialogWin = window.showModalDialog('modal.html',
 obj, "dialogwidth: 450; dialogheight: 300; resizable: yes"); // Showing the Modal Dialog
// Below Part will be executed after the dialog window is closed.
 document.getElementById('name').innerHTML = dialogWin.name;
 document.getElementById('url').innerHTML = dialogWin.url;
 document.getElementById('dynText').innerHTML = 'Returned Values are:';
 }
The above method, ‘showModal()’ will open a modal dialog window, with an array of information into it. The array object used here is ‘obj‘.

Send the Data back to the Parent window

window.returnValue
The above mentioned .returnValue will be used to send the data back to the parent window.
window.returnValue = {key:'value',key2:'value2'};
Sample implementation is given below. There are two files;. index.html and modal.html.
index.html
<html>
 <head>
 <script type="text/javascript">
 function showModal()
 {
 var obj = [{"name":"tutorials2learn","url":"http://www.tutorials2learn.com"}, {"name":"sampleName","url":"http://www.sampleURL.com"}, {"name":"sampleName2","url":"http://www.sampleURL2.com"},{"name":"sampleName3","url":"http://www.sampleURL3.com"}] // Object to be sent the modal dialog
var dialogWin = window.showModalDialog('modal.html',
 obj, "dialogwidth: 450px; dialogheight: 300px; resizable: yes"); // Showing the Modal Dialog
// Below Part will be executed after the dialog window is closed.
 document.getElementById('name').innerHTML = dialogWin.name;
 document.getElementById('url').innerHTML = dialogWin.url;
 document.getElementById('dynText').innerHTML = 'Returned Values are:';
 }
 </script>
</head>
 <body >
 <p id="dynText" >Sending Object: <em>[{"name":"tutorials2learn","url":"http://www.tutorials2learn.com"}, {"name":"sampleName","url":"http://www.sampleURL.com"}, {"name":"sampleName2","url":"http://www.sampleURL2.com"},{"name":"sampleName3","url":"http://www.sampleURL3.com"}]</em></p>
 <p>
 Name: <em id="name"></em><br>
 Url: <em id="url"></em>
 </p>
 <a href="#" onclick="showModal();" >Show Modal</a>
</body>
 </html>
modal.html
<html>
 <head>
<script type="text/javascript">
 // generate Select Box with values received from the parent window.
 function genOptions(){
 var opts = window.dialogArguments;
 var selBox = document.getElementById('selOpt');
 for(var i =0;i<opts.length;i++){
 selBox.options[i] = new Option(opts[i].name,opts[i].url);
 }
 }
 // Send the selected Values as an Object to the parent window.
 function sendValues(){
 var selBox = document.getElementById('selOpt');
 sendObj = {name:selBox.options[selBox.selectedIndex].text,url:selBox.value};
 window.returnValue = sendObj;
 window.close();
 }
 </script>
</head>
 <body  >
 <p>choose your option:<br >
 <select id="selOpt">
</select>
 </p>
 <a href="#" onclick="sendValues();" >Save</a>
 <script>
 genOptions();
 </script>
 </body>
 </html>
Run, index.html t

No comments:

Post a Comment