retrieve value from javascript function in codebehind - javascript

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;

Related

Calling C# code from JavaScript in SharePoint

Ok here's what I'm trying to do.
I have this custom action (button on my SharePoint-ribbon). This should call a Javascript, which in turn should call a C#-code.
I have the following:
<CustomAction
Id="Ribbon.Documents.DocsetZip"
Title="Download Document Set as ZIP"
RegistrationType="ContentType"
RegistrationId="0x0120D520"
Location="CommandUI.Ribbon"
>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Documents.Share.Controls._children">
<Button Id="Ribbon.Document.Share.DownasZip"
Sequence="20"
Command="Ribbon.ManageDocumentSet.MDS.Manage.DownZip"
Alt="Download as ZIP"
Image16by16="/_layouts/images/zipfile16x.png"
Image32by32="/_layouts/images/zipfile32x.png"
LabelText="Download as ZIP file"
ToolTipTitle="Download as ZIP file"
ToolTipDescription="Compress the document set and download"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="Ribbon.ManageDocumentSet.MDS.Manage.DownZip"
CommandAction="javascript:__doPostBack('DownloadZipDelegateEvent', '')" />
</CommandUIHandlers>
</CommandUIExtension>
And i have a class:
public class MyRibbonDelegateClass : WebControl
{
protected override void OnLoad(EventArgs e)
{
this.EnsureChildControls();
base.OnLoad(e);
if (this.Page.Request["__EVENTTARGET"] == "DownloadZipDelegateEvent")
{
using (TextWriter writer = File.CreateText("C:\\temp\\perl.txt"))
{
//
// Write one line.
//
writer.WriteLine("First line");
//
// Write two strings.
//
writer.Write("A ");
writer.Write("B ");
//
// Write the default newline.
//
writer.Write(writer.NewLine);
}
}
}
It seems my code gets executed, but I cannot find my file anywhere.
What am I missing?
you can use __DoPostback to invoke a server side hit from javascript.
<script type="text/javascript">
function ServerPostWithParameter(parameter)
{
__doPostBack('btnSave', parameter)
}
</script>
in server side,
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // this is your parameters
// Request["__EVENTTARGET"]; // this is your button
}
You can just create an HttpHandler with your server-side code and call it with parameters from JavaScript.
E.g. create an ~sitecollection/_layouts/15/MyCustomHandler.ashx and call it from JavaScript like this (SharePoint 2013 uses virtual path to layouts directory as '_layouts/15', SharePoint 2010 -- just '_layouts'):
$.get(_spPageContextInfo.siteServerRelativeUrl + '/_layouts/15/MyCustomHandler.ashx?Param1=Value1&Param2=Value2');
I've solved it as follows :
function getOutlook() {
var xmlHttpReq = createXMLHttpRequest();
xmlHttpReq.open("GET", _spPageContextInfo.siteServerRelativeUrl + "/_layouts/SendDocuments/MyCustomHandler.ashx?ItemsArray=" + fileRefArray, false);
xmlHttpReq.send(null);
}
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}

When I use window.location.href ,then my another function not calling .Following is my javascript code

I am using Following code..
When I click on the link, the javascript Hello() function is invoked
I want to use window.location.href
But when I use this the following __doPostBack('Button2_Click'), it does not work.
But when remove window.location.href from the following code then __doPostBack('Button2_Click') does work.
<script type="text/javascript">
function Hello(clicked_id) {
var abc = "http://localhost:2621/OrgChart.aspx?id" + clicked_id;
window.location.href = abc;
__doPostBack('Button2_Click');
return false;
}
</script>
<a id="A1" href="javascript:Hello();">LINK</a>
This is my code behind code...
public partial class WebForm17 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);//This is important to make the "__doPostBack()" method, works properly
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
Button2_Click(this, new EventArgs());
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "Method called!!!";
EmpInfo emp = new EmpInfo();
DA_EmpInfo da_emp = new DA_EmpInfo();
List<EmpInfo> lei = da_emp.GetAllEmployeeInfoByEmpId("MJ-IB-1");
DetailsView1.DataSource = lei;
DetailsView1.DataBind();
}
}
I guess, __doPostBack is making a request to the server and you break it by using window.location.href = abc;.
You should use some callback from this request to redirect to your url.
try to use setTimeOut function
setTimeout(function () {
window.location.href = abc;
}, 1000);
this will wait 1 second for finish of __doPostBack() function.
Or if you don't want to use timeOut, paste window.location.href = abc; line to end of the __doPostBack() function.

Change Gridview Textbox's visible property true false on DropdownLists's Selected index change event using javascript not working

I am making Gridview's Textbox visible true or false when user changes Dropdownlists selectedIndexchange event for that i have done following code
My .CS File code is as below:
protected void gvTaskList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hdn = (HiddenField)e.Row.FindControl("hdnStatus");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlStatus");
TextBox txt = (TextBox)e.Row.FindControl("txtVal");
if (ddl != null)
{
ddl.Items.Add("Not Started");
ddl.Items.Add("In Progress");
ddl.Items.Add("Complete");
if (hdn != null)
{
ddl.SelectedValue = hdn.Value;
}
//ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Attributes.Add("onChange", "return myFun(" + "'" + txt.ClientID + "'" +");");
}
}
}
catch (Exception ex)
{
Utility.ErrorList("EmpTaskList--RowdataBound", ex.ToString());
}
}
Note: My combobox and textbox both are in EditTmplate
Javascript code is as below
<script type="text/javascript">
function myFun(txtControl) {
var v = document.getElementById("<%=" + txtControl + "%>");
alert(v);
}
When i m changing dropdownlist index function is called and alert is showing null.
So can anyone please suggest me what i m doing wrong??
I don't think you want the server-side tags in your getElementById call:
var v = document.getElementById(txtControl);

pass a variable value from code behind to javascript

I have a hidden variable in my .aspx page.
input type="hidden" runat="server" id="isdup"
Now in code behind i check for certain conditions and assign isdup a value accordingly. However, this may not help you much but this is what i do in code behind.
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Now I need to access the isdup inside javascript. However the problem has been that those values are not passed and isdup is null.
var showus= document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
if(showus == "true")
{
Showduplicate();
}
So, kindly let me know the mistake i have been doing?
Hve you tried with:
var showus= document.getElementById('<%=isdup.ClientID %>').value;
update
is javascript at the end of the page?
update
try to put this code in the page:
<asp:HiddenField ID="isdup" runat="server" Value="eee"/>
<script>
var showus = document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
</script>
this works for me!
update
in page_load...
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
my example:
protected void pagesTree_NodeClick(object sender, RadTreeNodeEventArgs e)
{
PageStructure page = pageService.GetPage(Guid.Parse(e.Node.Value));
this.LoadPageData(page);
isdup.Value = "xxx";
}
update
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Try this JQuery code.
var showus= $("#<%=isdup.ClientID %>").val();
Replace your input field and try this with jquery code
UPDATED
<asp:HiddenField ID="isdup" runat="server" EnableViewState="true" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"/>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var showus = $("#<%=isdup.ClientID %>").val();
alert(showus);
if (showus == "true") {
Showduplicate();
}
});
</script>

Execute Server Side from Client Side

I want to execute the Add button click event(server side) from client side.
This is my javascript function
function validateinput() {
var arrTextBox = document.getElementsByTagName("input");
var retVal = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type == "text" && arrTextBox[i].value == "") {
retVal = 0;
}
}
if (retVal == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
return true;
__doPostBack(btnAddItem);
}
}
I am calling the server side code only when alert("Validation Sucess") and returns true.
This is my server side code
protected void Page_Load(object sender, EventArgs e)
{
txtbox1.Attributes.Add("onkeydown", "if(event.keyCode) {if (event.keyCode > 57 && event.keyCode <= 90) return false; } else {return true};");
if (!IsPostBack)
{
//The code is too big to be posted
}
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
if (btnAddItem.Text == "Add Item +")
{
if (textbox1.text== "")
{
Addtogrid();
}
}
}
}
Am I doing it the right way? as I am not getting the expected results. Also I get an error at Page.GetPostBackEventReference(btnAddItem); saying ClientScript is a recommended way . When I try to use ClientScript.GetPostBackEventReference(btnAddItem); it throws an error stating ClientScript is not recognised.
Please help
The onclick event of an asp:button object will call the client validation if you set it up with a validtion control. If you have not set up the onclick event to the button it is not going to know what method to call. If you have set up the onclick then the javascript call is not needed. If you set up a validation control to use the validation script and the client side validation .net will handle the postback call. And looking at your script you may be better served using a required field validator than your custom script.
Are you sure you need the GetPostBackEventReference code in the page load method? _doPostBack() doesn't the target object to be referenced, just the name.
Edit: Why are you calling return true before calling _doPostBack()?
Edit 2: There are 2 ways to call GetPostBackEventReference, 1) from your .NET code here but this is an obsolete method and the client side script version is recommended, 2) from your client side script here. I can't tell which method you are using because you didn't post the page load code. I don't see a reason to call it based on the other code you posted. The call to _doPostBack() can operate without getting the post back reference for a control.
Remove the call to GetPostBackEventReference and change your javascript to look like this:
function validateinput() {
var arrTextBox = document.getElementsByTagName("input");
var ddlTextBox = document.getElementsByTagName("select");
var retVal = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type == "text" && arrTextBox[i].getAttribute("IsMandatory") == "Y" && arrTextBox[i].value == "") {
retVal = 0;
}
}
if (retVal == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
__doPostBack('btnAddItem', '');
return true; // This shouldn't be needed but it does need to come after _doPostBack()
}
}
Edit 3: Try the following code for the button:
<asp:Button ID="btnAddItem" runat="server" onclick="btnAddItem_Click" OnClientClick ="javascript:validateinput(); return false;" Text="Add Item +" Width="85px" />
The OnClientClick code needs to return false if you don't want it to post back to the form. Even if you return false from a called JavaScript method, it will still post back. This has never made sense to me but I've learned it through repeatedly having this same issue.

Categories

Resources