I need a code segment to call a javascript function recordInserted() which shows up an alert, from my following code behind method,
protected void add_Click(object sender, EventArgs e)
{
String gradename = txt_gradename.Text;
int allocatedclasses = Int32.Parse(txt_allocatedclasses.Text);
String headid = txt_head_id.Text;
int numberofstudents = Int32.Parse(txt_numberofstudents.Text);
db = new DBConnection();
db.getConnection();
db.executeUpdateQuery("INSERT INTO Grade (GradeName,AllocatedClasses,GradeHeadID,NumberOfStudents) VALUES ('"+gradename+"','"+allocatedclasses+"','"+headid+"','"+numberofstudents+"')");
//I Need to call it from here before redirecting
Response.Redirect("AdminReferenceGradeAdd.aspx");
}
Please helpp me with this.
I have tried the following but never worked,
Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted()",true);
This will never work .. beacuse you are saying to redirect.
when you say Response.Redirect every thing which you have prepared to send is not sent,instead response is redirect to a new page.So your client script never reaches to browser.
you can use it like this :-
Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted();window.location.href='wwW.google.com'",true);
use window.location.href to redirect to your page("yourpage.aspx').
Try this:
ClientScript.RegisterClientScriptBlock(typeof(Page), "Call your function", "recordInserted()", true);
Or try calling Javascript function after a second:
ClientScript.RegisterClientScriptBlock(typeof(Page), "Call your function", "setTimeout('recordInserted()', 1000)", true);
Related
JS code:
function save( ref, text){
$.post("save.aspx", {cc:"us", ref:ref, text:text}, function(data){
$("[data-ref='"+ref+"'] .loader").animate({opacity:0},500,function(){
$(this).parent().removeClass("saving");
$(this).remove();
});
});
}
CS file Code:
public partial class save : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// $_REQUEST['cc'];
// HttpContext.Current.Response
string strcc = Request.Form["cc"];
string strRef = Request.Form["ref"];
string strtext =Request.Form["text"];
}
}
Unable to get the values passed from JS code to next page, what i'm doing wrong here?
Your code is fine. I'm almost sure that ASPX page code executes before JS function calls it. You may trace this with Fiddler
So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()
Hi i have the following pagemethod, however it dues not seem to be working, i tried debugging it and it does not hit the method. Here is what my method looks like;
function InsertStatus() {
var fStatus = document.getElementById('<%=txtStatus.ClientID %>').value;
PageMethods.InsertStatusUpdate(fStatus, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
And my codebehind;
[WebMethod]
public static string InsertStatusUpdate(string fStatus)
{
string Result = "";
int intUserID = -1;
if (String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
HttpContext.Current.Response.Redirect("/login");
else
intUserID = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
if (string.IsNullOrEmpty(fStatus))
return Result = "Please enter a status";
else
{
//send data back to database
return Result = "Done";
}
}
When i click my button it goes straight through the onError Method. Can anyone see what i am doing wrong?
I found the problem i needed a [System.Web.Script.Services.ScriptService] above the method, due to the fact it is being called by a script. Thanks for all the suggestions.
If I were to guess, I would focus on this:
intUserID = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
The best way to solve this is set a breakpoint and start walking through the code. When you run a line and are redirected to the error page, you have found your problem.
The reason I picked that line, is the user is a string. Now, it may be your users are numbers, but it could also be including a domain user == "mydomain/12345", which is not an integer, even if the user part of the string is.
As far as I know, you can't Response.Redirect in a PageMethod.
Return a string of the redirect URL and then use JavaScript document.location.href to handle the redirection.
EDIT: I've just seen that you tried debugging and the method isn't hit: ensure your ScriptManager has EnablePageMethods set to true:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
I need to use the javascript functions to show and hide an element on my page, but calling it from within a C# method. Is this possible?
EDIT : I tried RegisterStartupScript (see below) but this did not hide the elements as I had hoped :
HidePopup("CompanyHQSetup", "$('#<%=DivDataProvider.ClientID %>').hide();$('#<%=modalOverlay.ClientID %>').hide();");
private void HidePopup(string Key, string jscript)
{
string str = "";
str += "<script language='javascript'>";
str += jscript;
str += "</script>";
RegisterStartupScript(Key, jscript);
}
EDIT : Got around this by using a hidden field boolean to determine whether or not to hide or show the elements
Yes, check out RegisterClientScriptBlock.
Here's a snippet taken from that link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
}
One is server side, the other is client side. They can pass variables to each other (Javascript to ASP would be via forms/querystring/cookies and ASP to JS done via response.writing variables), but they can't directly interact.
you can use page.RegisterClientScript method to do that go on the following url
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx
and give it a try
Javascript is client side, c# is server side. You can't call javascript directly from C#. Take a look at Comet though, it will show you how you can push data from the HTTP server to the webpage.
I am trying to call a JavaScript function from my ascx control code behind in the catch block.
I have tried the below two ways but they don't seem to work.
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "script", "test();", true);
ScriptManager.RegisterStartupScript(Page, GetType(), "err_msg", "alert('error');", true);
The function is called if I place the code Under "PageLoad" but doesn't get called when placed in catch block.Should I do any different to call a JavaScript function from catch block. Please suggest.
Thanks
Have you tried this?
Page.ClientScript.RegisterStartupScript(typeof(string), "script", "test();", true);
I cant recall off the top of my head if that is equivalent to the ScriptManager option in the question.
Also you need to make sure that the "script key" value you are passing in is unique otherwise asp.net will discard all but the first instance of the registered script with the same key.
might want to try this:
.cs
public String ScriptToRun = "test();";
.aspx
$(document).ready(function() {<%=ScriptToRun %>}); //or you can register event to document mannually
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
update:
I tried the following code, it works in my case. could you please provide more detail?
.cs
public String script = "";
protected void Page_Load(object sender, EventArgs e)
{
throwExcep();
}
private void throwExcep()
{
try
{
throw new NotImplementedException();
}
catch (Exception e)
{
script = "console.log('exception throws from backend message: ["+e.Message+"]')";
}
}
.aspx:
<script>
$(document).ready(function(){
<%=script %>
});
</script>
Javascript does not like at all special characters and NewLine (\r\n) characters. Replace all of those and it will work.
Example:
string test = msgError.Replace("'", "");
test = Server.HtmlEncode(test).Replace(Environment.NewLine, "<br />");
Page.ClientScript.RegisterStartupScript(
typeof(string),
"MyKeyCatch",
//script,
"showErrorMessage('"+test+"');",
true);
What is the catch block for and where is it?
If code in a catch block is executed it usually means that something failed, maybe that failure also is the reason the JS call does not go through.