int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i + ")", true);
function f2(i) {
if (i == 1) {//CariKartHareketleri
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
}
else if (i == 2) {//islemler
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
else if (i == 3) {//hizmet listesi
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
}
it says i is undefined when I debug the code in f2(i).What am i doing wrong?
EDIT: I learned many things from this problem, but I still do not have an answer.I tried every idea given in the answers but i is still undefined...
EDIT: I still have no solution for undefined reasons :), but the answer I accepted would normally be my solution.
Have you tried debugging the server-side code to see if
int i = Convert.ToInt32(Session["sayfaTuru"]);
is giving you what you want in the first place?
Well seeing as how the above has been checked, I went ahead and created my own test, and it worked just fine. Here's the test I used:
JS:
<script type="text/javascript">
function f2(i, hiddenFieldId, updatePanelId) {
console.log(i + ', "' + hiddenFieldId + '", "' + updatePanelId + '"');
var hiddenField = window.opener.document.getElementById(hiddenFieldId);
switch (i) {
case 1: //CariKartHareketleri
hiddenField.value = "hello world 1";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
break;
case 2: //islemler
hiddenField.value = "hello world 2";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
case 3: //hizmet listesi
hiddenField.value = "hello world 3";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
default:
alert("error");
break;
}
}
</script>
C#:
Session["sayfaTuru"] = 2; // initialize for testing purposes
int i = Convert.ToInt32(Session["sayfaTuru"]);
string script = string.Format("f2({0}, '{1}', '{2}');",
i.ToString(),
this.HiddenField1.ClientID,
this.GridRefreshPanel.UniqueID);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", script, true);
console.log Output:
2, "HiddenField1", "GridRefreshPanel"
ClientScript.RegisterStartupScript takes a script definition, not an invocation.
Since you want to define the function externally, use this method instead:
ClientScript.RegisterClientScriptBlock(this.GetType(), "RefreshOpener", "MyJavaScriptFile.js", true);
To execute the JavaScript function f2 with parameter Session["sayfaTuru"] on button click, use the following (not tested):
In Page_Load, add the JavaScript file which contains the definition for f2:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(...);
// Do other stuff
}
Then add the actual button click listener which will invoke f2:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="f2(<%=Session['sayfaTuru']%>);" />
I think you may be getting an Exception thrown in your code-behind. You're trying to concatenate strings, but i is an integer. Try this instead:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i.ToString() + ")", true);
Though I would actually prefer to use String.Format:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", String.Format("f2({0})", i), true);
Related
I would like to call javascript function in case something in my code behind would happen.
If it is like the code below it works fine after postback alert windows shows and says it correctly. But in case I remove the comment from else block none of those two scripts in else block will happen?
Is there any limit on how many of these action could I make from codebehind?
if (condition) {
if (condition2) {
var message = "It happened !";
Page.ClientScript.RegisterStartupScript(this.GetType(), "yep1", "alert('" + message + "')", true);
}
} else {
var msg = "It does not work like that";
Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('" + msg + "!')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope2", "alert('" + msg + "')", true);
}
This way it will work. As the name of the function says, it register the startup script so you are changing it instead of inserting 2. In this way it will do both ^^
if (condition)
{
if (condition2)
{
var message = "It happened !";
Page.ClientScript.RegisterStartupScript(this.GetType(), "yep1", "alert('"+message+"');", true);
}
}
else
{
var msg = "It does not work like that";
Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('"+msg+"!'); alert('" + msg + "');", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('"+msg+"!')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope2", "alert('" + msg + "')", true);
}
How can i execute a C# method from JavaScript Code without refreshing the page?
this is the function that i want to execute:
protected void submitData(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
string worker = workerNameInput.Text;
string project = projectNameInput.Text;
string status = statusInput.Text;
string color = colorInput.Text;
if (worker.Equals("") || project.Equals("") || status.Equals("") || color.Equals(""))
return;
try
{
conn = new MySqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
string com = "insert into " + table + " values ('" + worker + "','" + project + "','"+ status + "','"+ color + "');";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(com, conn);
string res = command.ExecuteNonQueryAsync().ToString();
Console.WriteLine(res);
Console.WriteLine("Insert command pass successfully");
}
catch (Exception ex)
{
Console.WriteLine("Failed to update database with \"insert\" command");
Console.WriteLine(ex.Message);
}
}
and i know that i should use
public partial class Home : System.Web.UI.Page, IPostBackEventHandler
and
public void RaisePostBackEvent(string eventArgument)
{
submitData(null, null);
}
inside the JS i used this code:
project.updateTable = function() {
var projectName = project.projectName();
var workerName = project.workerName();
var status = project.status();
var color = project.color();;
if (projectName == "" || workerName == "" || status == "" || color == "")
return;
project.rows.push({ projectName: ko.observable(projectName), workerName: ko.observable(workerName), status: ko.observable(status), color: ko.observable(color) });
project.projectName("");
project.workerName("");
project.status("");
project.color("");
var argumentString = projectName + "," + workerName + "," + status + "," + color;
var pageId = '<%= enterToDB.ClientID%>';
__doPostBack(pageId, argumentString);
};
This is how i configure my button:
<p><asp:Button runat="server" ID="enterToDB" Text="Add Project" data-bind="click: updateTable" onmouseover="this.style.background='orange', this.style.color='darkslateblue'" onmouseout="this.style.background='darkslateblue', this.style.color='orange'" /></p>
Can you correct my mistakes please?
and show me where i'm wrong?
You can use ASP.NET WebForm's UpdatePanel control to run the code-behind async. This is commonly known as "AJAX" (Asynchronous JavaScript and XML) or "XHR" (XML HTTP Request), and is built-in to the WebForms framework.
Here's a great resource on MSDN to get you started: https://msdn.microsoft.com/en-us/library/bb399001.aspx
It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.
Javascript to C#
-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }
-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />
C# to Javascript
-------C# code--------------------
object [] MyArgs = { "Hello" } ; WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;
-------Javascript----------------
function MyJsFunction(s) { alert(s) ; }
I am new to Asp.Net.
I've found somewhere how to make in Asp.net/Javascript a MessageBox:
public static void Show(String str,Page pg, Object obj)
{
string s = "<SCRIPT language='javascript'>alert('" + str.Replace("\r\n", "\\n").Replace("'", "`") + "'); </SCRIPT>";
Type cstype = obj.GetType();
ClientScriptManager cs = pg.ClientScript;
cs.RegisterClientScriptBlock(cstype, s, s.ToString());
}
So the question is: is there a way (using a similar code) to get an answerBox (yes/No) displaying a message a getting the yes/No answer?
thanx in advance
Yes - use confirm instead of alert in your script. See for example http://www.w3schools.com/jsref/met_win_confirm.asp
Javascript example:
(function () {
var r = confirm("OK or Cancel ?");
if (r == true) {
alert("You pressed OK!");
} else {
alert("You pressed Cancel!");
}
})();
I have some other javascript functions that are being set on the onfocus and onblur events of the textbox that I am using. In these functions it calls a generic javascript function that is not related to any controls. I want to know how to just simply spit this function out to the html of the page from the code behind. Something like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "?????", getCounter);
EDIT: Here is what I mean
public class MVADTextBox : TextBox
{
protected override void OnLoad(EventArgs e)
{
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetCounter(input)", getCounter);
var onBlur = "<script language=\"javascript\"> function PopulateField(input) {if (input.value == \"\") {input.value = input.defaultValue; input.className = 'sampleText'; } } </script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnBlur", onBlur);
}
}
The on blur method is getting sent to the page.
Answer:
I believe that Page.ClientScript has been deprecated. You should be using ClientScriptManager.
Replace your "?????" with the name of the script. Honestly, the name of the script is almost useless (unless you need to check for its existence later on).
ClientScriptManager.RegisterStartupScript(this.GetType(), "myCount", getCounter);
Usage Clarification:
//You must surround your code with script tags when not passing the bool param
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"<script>alert('Hey')</script>");
// The last param tells .Net to surround your
// code with script tags (true) or not (false)
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"alert('Hey')", true);
Additional Information:
Signatures from MSDN:
public void RegisterStartupScript(
Type type,
string key,
string script
)
public void RegisterStartupScript(
Type type,
string key,
string script,
bool addScriptTags
)
See: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
I think you need to use the ClientScriptManager.RegisterClientScriptBlock method
Try this
EDITED:
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
this.TextBox1.Attributes.Add("OnFocus", "GetCounter(this);");
if (!ClientScript.IsClientScriptBlockRegistered("getCounter")) {
ClientScript.RegisterClientScriptBlock(this.GetType(), "getCounter", getCounter, false);
}
You would put the actual function definition, which you already have in getCounter. Note that the second parameter which you currently have as "????", as James pointed out, is for the script's key, which must be unique from all other scripts registered for this type. The third parameter is the script itself, and the fourth determines whether script tags are to be added, which needs to be false, since you already added them.
Page.ClientScript.RegisterStartupScript(this.GetType(),
"someKeyForThisType", getCounter, false);
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>