I have a variable named "tempVariable" in my jquery file.
now I need to change its value from code behind in c#.
What I have done till now is
in my C# code
public void changeValueInJquery()
{
bool newVal = false;
Page.ClientScript.RegisterClientScriptBlock(
GetType(),
"key", "ChangeValue(" + newVal + ");", true);
}
my jquery code is as
function ChangeValue(value1) {
alert(value1);
tempVariable = value1;
}
The issue is that ChangeValue() function never gets hit.
Am I going wrong somewhere?
may be '...' is required to pass value...
Try this :
Page.RegisterStartupScript("changevalue", "<script>ChangeValue('" + newVal + "');</script>");
I would check in a JS debugger to see if you are getting any errors.
But generally try using Page.ClientScript.RegisterStartupScript(); instead if you are calling functions already present in the page. This will ensure that the script block is rendered at the bottom of the page and not for example before the ChangeValue function.
As other people have mentioned, this is nothing to do with jQuery.
Related
I have asp.net ajax page method like following,
[WebMethod]
public static string UnAuthVote(string vf)
{
return "";
}
and I am calling it like this,
PageMethods.UnAuthVote("alikhan", success1, error);
And my success1 and error method written like following,
function success1(response) {alert("");
return false;
}
function error(error) {alert("error");return false; }
The problem is it's invoking error event. Why my code is not calling pagemethod's success event.
help
Thanks
Well, I was using url rewriting. So that's why my pagemethods was not working.
Well
I set set_Path property like following
PageMethods.set_path("Auth/profile.aspx")
Now it's working as it should
It helps if you show the actual error, for example:
function success1(response)
{
alert(response);
}
function error(error)
{
alert(error);
}
You can also use a debugger or developer tools to identify the problem. The error may show on the Console tab. The debugger will allow you to troubleshoot more efficiently than editing code to show alerts but I understand that in some cases this is preferable. You can also write to the console by doing:
function success1(response)
{
if(window.console) console.log(response);
}
function error(error)
{
if(window.console) console.log(error);
}
The benefit of this is it doesn't get in the user's way, and is only visible if the console is open. Checking for window.console avoids exceptions thrown from logging to console if it is unavailable.
If you don't know the properties of the return objects you can iterate through them like this:
function error(error)
{
var output = [];
for(key in error)
{
output[output.length] = key.toString() + " = " + error[key];
}
alert(output.join('\n'));
}
I've been all over trying to find an answer to this, but every answer I found seemed to differ quiet a bit from what I really am looking for.
I need to check to make sure that two ASP Textboxes have been filled in before running a C# function that will do work on the text boxes.
Currently, I am using codebehind to check, but it is sloppy and has to postback to work.
So I have:
<td>Start Date (mm/dd/yyyy):</td><td><asp:TextBox ID="startDate" runat="server"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce1" runat="server" TargetControlID="startDate"></ajax:CalendarExtender>
<td>End Date (mm/dd/yyyy):</td><td><asp:TextBox ID="endDate"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce2" runat="server" TargetControlID="endDate"></ajax:CalendarExtender>
So I need a JS function to check if both field are empty, before using AJAX to run a C# program. I'm new to ASP and JS but this problem came through and figured it would be a (sort of) easy fix.
I would assume something like:
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s != '' && e != ''){
//Use ajax to run C# function
}}
should work. But I can't seem to find any examples close to it to get an idea of what I need to do when working ASP and not just HTML.
Any input is greatly appreciated! (I tried to be as clear as possible, getting tunnel vision..)
You are almost there
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s.value != '' && e.value != ''){
//Use ajax to run C# function
}
}
You should also need to check on the server side to ensure that the parameters being supplied are not null or empty.
This should work for you. I built an object to help keep things organized. Get the elements using the ClientID and store the reference in an object.
Whatever you're binding the handler to just needs to call Page.Handlers.CheckDates();
var Page =
{
Members:
{
startDate: document.getElementById('<%=startDate.ClientID %>'),
endDate: document.getElementById('<%=endDate.ClientID %>')
},
Handlers:
{
CheckDates: function ()
{
if (Page.Members.startDate.value.length > 0 && Page.Members.endDate.value.length > 0)
{
Page.Ajax.ValidateDates();
}
}
},
Ajax:
{
ValidateDates: function ()
{
//Put you ajax code here
}
}
}
In addition to Kami's answer I believe asp.net automatically prepends a tag to all asp.net controls to distinguish them. If you haven't changed it yourself I believe the default is "ct100_". So if you're using jQuery and aren't use an ajax call to get the ClientID the selector would look something like "#ct100_idname".
http://www.asp.net/web-forms/tutorials/master-pages/control-id-naming-in-content-pages-cs
Edit:
You can also use an inline server call to get the ID of a asp.net control
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
I am calling javascript functions from C# using the WPF variant of the browser control via InvokeScript.
I can call my function once without any problems. But when I call it a second time, it throws the following error :
Unknown name. (Exception from HRESULT: 0x80020006
(DISP_E_UNKNOWNNAME))
The Code I am using is the following :
this.browser.LoadCompleted += (sender, args) =>
{
this.browser.InvokeScript("WriteFromExternal", new object[] { "firstCall" }); // works
this.browser.InvokeScript("WriteFromExternal", new object[] { "secondCall" }); // throws error
};
The javascript function is :
function WriteFromExternal(message) {
document.write("Message : " + message);
}
I can call C# functions from the page via javascript just fine and invoke from C#, just can't invoke a second time. Regardless of what function I call.
I do not understand why it would fail the second time.
Thank you
Edit :
Did the following test (javascript) :
function pageLoaded() {
window.external.tick();
window.external.tick();
window.external.tick();
}
window.onload = pageLoaded;
function WriteFromExternal(message) {
document.write("Message : " + message);
}
And this is the C# side :
private int i = 0;
public void tick()
{
invoke("WriteFromExternal", new object[] { "ticked"+ i++ });
}
public static void invoke(string method, object[] parameters)
{
mainInterface.browser.InvokeScript(method, parameters);
}
And still throws the same error (after the first call), this suggests that it does not matter from where it is called, invoking the function from C# will throw this error if done more than once.
I assume you did the same as me and put your scripts in the body. For some reason when you call document.write from wpf it completely overwrites the document. If instead of using document.write you append a child it works fine. So change your JavaScript function to be:
window.WriteFromExternal = function (message) {
var d = document.createElement("div")
d.innerHTML= "Message : " + message;
document.body.appendChild(d);
}
// call from c#
WriteFromExternal("test")
It's been a while since I did something similar, but from what I remember your code looks correct. However, I do remember using a slightly different pattern in my project. Instead of delegating back to a JS method on the page I would make my ScriptingHost methods return values
EX:
C#:
public string tick()
{
return "some stuff";
}
var msg = window.external.tick();
document.write(msg);
If you have more complex objects than simple strings you can serialize them to JSON and parse them into an object on the JS side.
var jsonObj = JSON.parse(window.external.someMethod());
Not sure if you have the luxury of being able to change your method signatures in your scripting object, but it's at least an alternative approach.
Also, in your current implementation, have you tried to do something other than document.write? Do you get the same error if you display an alert box?
I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}
I'm trying to call some function from my code behind in C#. I was searching how to do this and was able to call an alert to display when I wanted it to. However, I don't know how to call other things!
This is what I need to call from the code behind:
var paper = Raphael("paper1", 800, 800);
var Plan = paper.path("M100, 100 a 50, 50 0 0,1 50, 50 l -50 0 l 0, -50");
Plan.attr({ fill: "#FF6600" });
I've tried these on a plain HTML file but I'm not able to use it. I'm also using a master page and most of the examples I've found have been without master pages so I'm pretty lost on this.
Anyone can help?
Create a Javascript function in the .aspx page and then call the function from code behind like so:
Function in html Code
function dostuff()
{
// code here
}
C# code in code behind
protected void callmethod()
{
StringBuilder oSB = new StringBuilder();
Type cstype = this.GetType();
try
{
oSB.Append("<script language=javaScript>");
oSB.Append("dostuff();");
oSB.Append("</script>");
Page.ClientScript.RegisterClientScriptBlock(cstype, Guid.NewGuid().ToString(), oSB.ToString(), false);
}
catch (Exception ex)
{
throw ex;
}
finally
{
oSB = null;
}
}
Javascript can only be called on the client side. If you absolutely need to call it from your serverside, you can use a asp:HiddenField's value as a flag for when you need the javascript code executed upon returning, and then run the needed javascript if the requirements are met.
But its not a nice solution, you should probably try to separate the server and the client.
Hope this helps, in any case!