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>
Related
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;
I have a weird problem. I use JavaScript on a Sharepoint page. I reference following JavaScript code:
var statusId = '';
var notifyId = '';
function AddNotification(message) {
notifyId = SP.UI.Notify.addNotification(message, true);
}
function RemoveNotification() {
SP.UI.Notify.removeNotification(notifyId);
notifyId = '';
}
function AddStatus(message) {
statusId = SP.UI.Status.addStatus(message);
SP.UI.Status.setStatusPriColor(statusId, 'red');
}
function RemoveLastStatus() {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
function RemoveAllStatus() {
SP.UI.Status.removeAllStatus(true);
}
Then when the user clicks a button, a notification should appear with the message "please wait...". Before the calling C# method exits, it should remove the notification. Like this:
protected void SaveButton_Click(object sender, EventArgs e)
{
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "Notif", "AddNotification('" + Core.Classes.ResourceHelper.LoadResource(Core.Classes.ResourceName.PleaseWaitString) + "');", true);
//Busiess logic...
if (ActivityDate.SelectedDate == null || //Date required
ActivityProjectnumber.SelectedIndex == 0 || //Project number required
ActivityActivity.Text == string.Empty || //Activity description required
EndTime.SelectedDate.Hour < StartTime.SelectedDate.Hour || //
EndTime.SelectedDate.Hour == StartTime.SelectedDate.Hour && //Start time should not be less or equal end time
EndTime.SelectedDate.Minute <= StartTime.SelectedDate.Minute) //
{
StatusSetter.SetPageStatus(Core.Classes.ResourceHelper.LoadResource(Core.Classes.ResourceName.CheckRequiredFieldsString), Core.Classes.ResourceHelper.LoadResource(Core.Classes.ResourceName.WarningString), this.Controls);
return;
}
//If business logic passed, save item.
SaveItem();
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "Notif", "RemoveNotification();", true); //Problem lies here...
}
The notification is displayed when the user clicks the button. But it doesn't disappear. I debugged the code and the corresponding line is definitely being executed. I suspect it has something to do with me using ScriptManager.RegisterStartupScript two times in one method. But I don't know how to do it otherwise.
You need to give different names to each script (the 3rd parameter of RegisterStartupScript).
I have following code .
In asp.net , I set session variable .Then pass it to javascript for modification .
In javascript I can read session variable value and return modified value in TextBox1 .
In asp.net again , I receive modified session variable value and store it in session variable .
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
But my aim was –
Within javascript function itself I should be able to modify session variable .
And I don’t want to use submit button.
Using cookie i can preserve value . Submit button is also not required . So this code has solved my purpose .
<script language="javascript" type="text/javascript">
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for (i = 0; i < ca.length; i++)
{
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
function restore(){
var sId = readCookie('sessionId');
document.getElementById("TextBox1").value = sId ;
}
function backup() {
var sId = document.getElementById("TextBox1").value;
writeCookie('sessionId', sId, 3);
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
function TextBox1_TextChanged() {
backup();
}
</script>
<body onload="restore()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack="True" onchange="TextBox1_TextChanged()" ></asp:TextBox>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
Loading();
}
void Loading (){
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
No, session variables cannot be modified on client side directly and expect to change on server. Atleast, AJAX request has to be made to persist the session value.
And based on your current code, I am not understanding significance of session variable. You're just appending text box value with session variable and submitting the form.
So, it would be direct statement without needing client side script, i.e,
//page_load
{
Session["Mytest"] = test;
}
//page_submit
{
Session["Mytest"] += txtName.text;
}
You can define a web method in asp.net or action in MVC and set session inside it from parameter passed
[HttpPost]
public bool SetSessionAction(string param)
{
Session[sessionName] = param;
return true;
}
then call method or action using $.ajax or $.post from jquery.
var paramValue = 'some data';
var targetUrl = "#Url.Action("SetSessionAction", "ControllerName" )";
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: targetUrl,
data: { param: paramValue },
success: function (s) {
alert('Set Session is: ' + s);
}
});
Good Luck
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);
i have two dropdowns and thier hidden field each on codebehind im adding javascript onchange event by attribute.add and a button to perform some dynamic actions like adding controls at runtime
when i click that button dropdown are reset. In order to maintain state i have a hidden field with dropdown i get selectedvalue from hidden field but by coding DDCity.Items.FindByValue doesnt seems to work Can anyone help?
protected void Page_Load(object sender, EventArgs e)
{ DDCountry.Attributes.Add("onChange", "javascript:BufferAddDDCountry('" + DDCountry.ClientID + "');");
DDCity.Attributes.Add("onChange", "javascript:BufferAddDDCity('" + DDCity.ClientID + "');");}
if (hiddenDDCityValue.Text != "0")
{
DDCity.Items.FindByValue(hiddenDDCityValue.Text).Selected = true;// this dont work
}
if (!IsPostBack)
{ this.populateCountry();populateCity();}
javascript code
<script type="text/javascript">
function BufferAddDDCountry(objDd) {
try {
var objHidden = document.getElementById('hiddenDDcountryValue');
objHidden.value = document.getElementById(objDd).value;
} catch (e) {
alert(e);
}
};
function BufferAddDDCity(objDd) {
try {
var objHidden = document.getElementById('hiddenDDCityValue');
objHidden.value = document.getElementById(objDd).value;
} catch (e) {
alert(e);
}
};
</script>
i atlast made it working in javascript hope this will help others here is the code
codebehind pageload
ScriptManager.RegisterStartupScript(UpdatePanel, this.GetType(), "Dropdownselectedvaluechange", "javascript:setSelectedValue('" + DDCity.ClientID + "','" + hiddenDDCityValue.Text + "');", true);
javascript code
function setSelectedValue(dropdownList, selectedValue) {
var dropdown = document.getElementById(dropdownList);
for (var i = 0; i < dropdown.options.length; i++) {
if (dropdown.options[i].value == selectedValue) {
dropdown.options[i].value = selectedValue;
dropdown.options[i].selected = true;
break;
}
}
return;
}