Sharepoint 2010 XsltListViewWebPart on an application page - javascript

I'm trying to add an XsltListViewWebPart control to a sharepoint application dynamically.
When I run ShowDocumentList(pnlAdminCurrentDocuments) on Page_Load everything works fine.
However, if i call the same function on a ajax request, the control loads, but none of the events get fired (i.e. sorting, expanding tree view etc)
XsltListViewWebPart wp;
private void ShowDocumentList(Panel panel)
{
try
{
ShowMessage("<p>No documents to show</p>");
string meetingURL = "http://rl01/sites/nmc/FullMonty";
string meetingId = "6d39de81-a7f7-4cff-9c94-5d2893526dc5";
if (!string.IsNullOrEmpty(meetingURL) && !string.IsNullOrEmpty(meetingId))
{
using (SPSite site = new SPSite(meetingURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("Meeting Documents");
if (list == null)
return;
SPView view = null;
try
{
view = list.Views["Submitted"];
//view = list.Views[0];
}
catch { }
if (view == null)
{
//todo - replace with toolbx message
ShowMessage("Cannot view documents");
}
else
{
wp = new XsltListViewWebPart();
wp.ChromeType = PartChromeType.None;
wp.ListId = list.ID;
wp.ViewGuid = view.ID.ToString();
wp.WebId = web.ID;
wp.XmlDefinition = view.GetViewXml();
wp.XmlDefinition = wp.XmlDefinition.Replace("MEETING_ID", meetingId);
//SetToolbarContext(web);
panel.Controls.Clear();
panel.Controls.Add(wp);
}
}
}
}
}
catch (Exception ex)
{
ShowMessage("");
}
}
The function actually gets the data and does everything but none of the client side functionality on the list view doesn't work. Throws a javascript error even when I mouse over the column names. If I add the control with a full postback without using ajax, everything works as expected.
protected void radAjaxMgr_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
ShowDocumentList(pnlAdminCurrentDocuments);
}
HTML markup is as follows
<telerik:RadAjaxManager ID="radAjaxMgr" runat="server" OnAjaxRequest="radAjaxMgr_AjaxRequest">
</telerik:RadAjaxManager>
<asp:UpdatePanel runat="server" ID="pnl1">
<ContentTemplate>
<asp:Panel ID="pnlAdminCurrentDocuments" runat="server" CssClass="i3q_DocumentListHldr submittedDocsPanel">
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Javascript function to raise the ajax call
function test()
{
var ajaxMgr = $find("<%= RadAjaxManager.GetCurrent(this).ClientID %>");
if (ajaxMgr)
{
ajaxMgr.ajaxRequest("Name1;Value1");
}
}
Thanks in advance :-)

Related

Call JavaScript from codebehind and inside the script call function in codebehind (PageMethods is undefind)

I need to call confirmation message box from codebehind as the user select data from dropdown list and when the selected data is 1 for example a confirmation box will appear to the user to confirm his action
so I did that as below in the code behind I called this JavaScript method:
if (dropdownlist1.SelectedValue == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);
}
The script function:
<script type="text/javascript">
function CallConfirmBox() {
if (confirm("هل تريد ان تفصل الباليت؟")) {
alert("سيتم فصل الباليت!");
PageMethods.getdata(onSuccess, onError);
function onSuccess() {
alert(data);
}
function onError() {
alert(errorMessage);
}
}
} else {
//CANCEL – Do your stuff or call any callback method here..
alert("done!");
}
}
And I've added the below line at the beginning of the HTML code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
and Here is the code behind function that is called from script :
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void getdata()
{
int nRowsCheck = cMDP.Update_Segregation_PalletPart(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Update_Segregation_Pallet(nPalletNo, nUserID);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_PalletPart_Delete(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_Pallet_Delete(nPalletNo);
}
}
}
}
But I've got the below error:
Page Methods is undefined when run the script !!
Please help as I need some support
First, you'll have to remove one } before the else in your JavaScript.
Change in your code-behind:
if (dropdownlist1.SelectedValue == "1")
For the main problem: Page Methods is undefined:
It seems from your comment that you're using a User Control (ascx). Page Methods cannot be used in a User Control. Please refer to these questions:
PageMethods is not defined
ASP.NET AJAX Page Methods from UserControl
The easiest solution is to use an aspx WebForm instead of an ascx User Control. That's what I've tested and worked.
Or you can use a WebService, as specified in the following question:
Alternate way to use page method inside user control asp.net
But the link to the sample is not working anymore.
Or you can try to use this project that tries to bring ASP.NET AJAX Page Methods to UserControls:
Control Methods for ASP.NET AJAX
You have two problems:
Change you javascript code:
PageMethods.getdata(onSuccess, onError);
function onSuccess(data)
{
alert(data);
}
function onError(data)
{
alert(data);
}
And you code behind getdata method must be a public static string function:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getdata()
{
//Do some things
return " Operations done successfully!";
}

Asp.net Call Code Behind with JavaScript

since i didn´t find any solution that helped me, i thought i asked.
I need a JavaScriptfunction with calls a method in my code-behind, and since i´m really new to this, i dont understand what am i doing wrong.
On my Master Page (Site.Master) i enabled PageMethods:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
And in the Content of my Page i have put the Script:
function reply_click(clicked_id) {
alert(clicked_id);
PageMethods.javascriptTest(clicked_id);
And now my method in the code-behind:
[WebMethod]
public void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I need that ID for later, when i have to do stuff in my database, but i´m always getting PageMethods undefined errors and i dont know why :/
EDIT: The Solution was indeed to make the WebMethod static, i just made a workaround, so i could use all the details i need for my db access
JavaScript:
function reply_click(clicked_id, clicked_name) {
// Schulungsdaten holen
var grid = document.getElementById("<%= SignGridView.ClientID %>");
var row = grid.rows[0];
var appointmentData = row.cells[clicked_id].innerText;
// Userdaten holen
var userID = document.getElementById("<%= UserData.ClientID %>").innerText;
PageMethods.javaScriptUserSignIn(appointmentData, userID, clicked_name, OnSucceeded, OnFailed);
location.reload();
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
Code-Behind:
[WebMethod]
public static string javaScriptUserSignIn(string appointmentData, string userID, string status)
{
string result = "";
SignIn sign = new SignIn();
result = sign.SignToTraining(appointmentData, userID, status);
return result;
}
Your javascriptTest method needs to be static
Try This:
[System.Web.Services.WebMethod]
public static void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}

retrieve value from javascript function in codebehind

How can I retrieve value from javascript function in codebehind, on page load ..
javascript function like :
<script type="text/javascript">
function isIFrame() {
var isInIFrame = (top.location != self.location);
if (isInIFrame) {
return "inside";
}
else {
return "outside";
}
}
</script>
and code behind like :
protected void Page_Load(object sender, EventArgs e)
{
string resutOfExecuteJavaScript = "";
// resutOfExecuteJavaScript = isIFrame(); // from javascript
if (resutOfExecuteJavaScript == "inside")
{
// do something
}
else
{
// do something
}
}
thank you.
You cannot directly call a client side javascript method from server side code . For that first you need to assign the function result to value of some hidden variable and then access it in server side
Suppose you have an hidden field like this
<input type="hidden" runat="server" id="hdnVal"/>
then you can set the value as below
document.getElementById("hdnVal").value=isIFrame();
then at serve side
string resutOfExecuteJavaScript = hdnVal.Value;
using _doPostBack, you can solve this one
<script type="text/javascript">
function isIFrame() {
var isInIFrame =(top.location != self.location);
var result;
if (isInIFrame) {
result="inside";
}
else
{
result ="outside";
}
__doPostBack('callPostBack', result);
</script>
</head>
In code behind section
protected void Page_Load(object sender, EventArgs e)
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (IsPostBack)
{
string eventTarget = this.Request["__EVENTTARGET"];
string eventArgument = this.Request["__EVENTARGUMENT"];
if (eventTarget != String.Empty && eventTarget == "callPostBack")
{
if (eventArgument == "inside"){
//do something
}
else if(eventArgument == "outside")
{
//do something
}
}
else
{
// set the button click
btnclick.Attributes.Add("onClick", "isIFrame();");
}
}
Below link will help you out to get more idea.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=203
in javascript file or your script add :
function SetHiddenVariable()
{
document.getElementById(inpHide).value= "value";
}
in .aspx add this tag:
<input id="inpHide" type="hidden" runat="server" />
in aspx.cs (c# file) add :
anyVariable = inpHide.Value;

How to call C# server side function from Javascript in ASP.net

I have a function in server side which fills a dropdownlist. I call this function with a button click on client side using PageMethods in Javascript like this:
<asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
<asp:Button runat="server" ID="SearchButton" Text="Search" OnClientClick="SearchButtonClick();return false;"/>
<asp:DropDownList runat="server" ID="SearchCityDropDownList" Width="100px"/>
And
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
Server side function:
[WebMethod]
public static string SearchButtonActivity()
{
string result = "Everything is OK!";
foreach (string value in getCityList())
{
SearchCityDropDownList.Items.Add(new ListItem(value));
}
return result;
}
When I run this code and click on the button it just shows the "Everything is OK!" alert and
dropdownlist still empty.
Please help me to solve this problem, I think this is a post back problem because when I debug the code, items of dropdownlist are full but they don't show up in the dropdown.
Thank you
This will not work, how you have it setup. You could do an update panel, but that would be overkill, IMO. The problem is that you are making an AJAX call which just goes back to the server and returns to the client. The page, and thus the control, never get back to the server to get re-rendered.
Instead, you need to bind the result from your onsuccess callback to your dropdown list. So your web method needs to change:
[WebMethod]
public static string SearchButtonActivity()
{
var result = new List<string>();
foreach (string value in getCityList())
{
result.Add(value);
}
return result;
}
And then your onSuccess client side callback needs to handle it:
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
SearchCityDropDownList.options.length = 0;
for (var i==0;i<result.length;i++) {
AddOption(result[i], i);
}
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
function AddOption(text, value) {
var option = document.createElement('option');
option.value = value;
option.innerHTML = text;
SearchCityDropDownList.options.add(option);
}
You can retrieve the value selected, server side in this fashion:
string selectedVal = Request[SearchCityDropDownList.UniqueID]
Thanks to this so post for the guidance: Getting the value of a DropDownList after client side javascript modification

Dropdownlist "Enable true" is not working Asp.net

I have set dropdown enable set to false in one button click and i will set enable="true" is not working in page load
here is my aspx
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" />
Here is my click event:
protected void btnTemplate_click(object sender, EventArgs e)
{
check.Value = "1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Load_functions()", true);
//txtAddJournal.Attributes.Add("Style", "display:block");
//btnUpload.Attributes.Add("Style", "display:block");
//if (fileuploader.HasFile)
//{
try
{
string Filename = Path.GetFileName(fileuploader.FileName);
//fileuploader.SaveAs(Server.MapPath("~/") + Filename);
// fileuploader.SaveAs(Server.MapPath("D:\\Req Sep16\\") + Filename);
OleDbConnection myconnectionini = default(OleDbConnection);
OleDbDataAdapter mycommandini = default(OleDbDataAdapter);
//if (fileuploader.PostedFile.FileName.EndsWith(".xls") == false & fileuploader.PostedFile.FileName.EndsWith(".xlsx") == false)
//{
// // lbl_Error.Text = "Upload only excel format";
// Response.Write(#"<script language='javascript'>alert('Upload only excel format');</script>");
// return;
//}
//else
//{
gvDetails.DataSource = null;
string pathToSave = HttpContext.Current.Server.MapPath("~/UploadFiles/") + "Copy of Database_HBM";
//fileuploader.PostedFile.SaveAs(pathToSave);
//strFilePath = "D:\\Files\\" + fileuploader.FileName;
string constrini = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + pathToSave + ";Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
// DataTable dt = new DataTable();
myconnectionini = new OleDbConnection(constrini);
mycommandini = new OleDbDataAdapter("select * from [Sheet1$]", myconnectionini);
ds = new DataSet();
mycommandini.Fill(ds);
gvDetails.DataSource = ds.Tables[0];
gvDetails.DataBind();
ddlJournal.SelectedIndex = -1;
ddlJournal.Enabled = false;
//ddlJournal.Attributes.Add("disabled", "disabled");
//}
}
catch (Exception ex)
{
string msg = ex.Message;
}
//}
}
And my page load event is
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
// ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>headerLock();</script>", true );
if (!IsPostBack)
{
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
ddlJournal.Enabled = true;
}
}
button :
<asp:Button ID="btnUpload" runat="server" Text="Template 1" OnClientClick="return Validate();"
OnClick="btnTemplate_click" CssClass="btn" />
but still my dropdown list is disable.
suggest me get a solution
thanks in advance
You can set dropdown list Enabled false from its control only like this
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" Enabled="false"/>
And the rest code should work fine.
Please mark it helps
Understand that your if-else condition in Page_Load() method is the main culprit. You're always setting ddlJournal.Enabled = true, no matter what. Seems like you didn't properly understand the concept of IsPostBack. ddlJournal is supposed to be disabled when IsPostBack is true, because that's what you want. Otherwise, it's supposed be enabled.
This is a very concise explanation about what IsPostBack is:
Postback in an event that is triggered when a action is performed by a contol on a asp.net page. for eg. when you click on a button the data on the page is posted back to the server for processing.IsPostback is normally used on page _load event to detect if the page is getting generated due to postback requested by a control on the page or if the page is getting loaded for the first time.
[a comment from http://forums.asp.net/t/1115866.aspx?What+is+IsPostBack ]
So based on that, you should change your code like the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
if (!IsPostBack)
{
//When IsPostBack is false, ddlJournal should be enabled
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
//Else, IsPostBack is true, so, ddlJournal should be disabled
ddlJournal.Enabled = false;
}
}
Also, you don't need this in your btnTemplate_click() method since you're doing this on page load:
ddlJournal.Enabled = false;

Categories

Resources