I have a function named "callfunction()" in JavaScript(Mypage.aspx) .This function should call another function "func()" in C# (Mypage.aspx.cs )
Something like this:
(in Mypage.aspx)
function callfunction()
{
// i have to call func() function here .....
}
</script>
(in Mypage.aspx.cs file)
public void func()
{
// My code goes here
}
I have researched alot because of this and i ended up so far with 2 conclusions:
1st was to use Json, but my superiors said clearly that they dont want me to do so.
2nd was that i cant do as i wish because of the client, server aspnet protocol
Please give me any kind of tip in how to do this, i am getting desperate
Ok....Try using page methods
First add a script manager on your aspx page
<asp:ScriptManager ID="scpt" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Then go to your aspx.cs page and declare a function something like
[System.Web.Services.WebMethod]
public static string ValidateUser(string emailId, string password)
{
//Your logic code
return returnString;
}
Then from your javascript call the c# method like
PageMethods.ValidateUser(email, password, CallSuccess_Login, CallFailed_Login);
And also in ur javascript create 2 call back functions CallSuccess_Login and CallFailed_Login
Hope it helps
If it's a webforms project (not MVC) and you don't want to use AJAX, you can use __doPostBack.
<script type="text/javascript">
function callfunction(parameter)
{
__doPostBack('func', parameter)
}
</script>
C#:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
var senderObject = Request["__EVENTTARGET"]; // func
if(senderObject == "func")
{
//call your function here, or write the implementation
}
}
below are the options available to you
If your using asp.net then use Ajax tools to create this
if you don’t want to user Ajax toolkit use JavaScript __doPostBack
or other option write server side function in the web service and call web method using JavaScript
Related
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'm new to integrating JavaScript into a web site, but I'm going to need it often in my web site.
Here is an example:
Assuming I have the function:
showAlert()
Say I have:
<div id="some_div">
</div>
Could someone provide me some kind of example that would do this:
If I have a button and the user clicks it, this should raise an event in the backend and call some method in my C# file. Then my C# file should be able to call some other javascript method of the front end which would call showAlert() and display the alert in the div.
This is what I can't seem to find any information on.
The basic idea of passing information to and from the server. Any help with this would be really appreciated.
Thanks
Your best bet is to use a framework like jquery, then bind to the button, call the service, and handle the response. The below is a quick example of this.
$(document).ready(function()
$('#Button1').bind('click', function () {
// This grabs the page you are in so that you can call it correctly
var pagePath = window.location.pathname;
var testId = $("#some_div").val();
var url = pagePath + "/TestService";
$.post(url, { id: testId },
function (data) {
showAlert(data);
}
});
};
});
First, you need to make sure the document is ready at some point. Bind allows the the button to be bound when the document loads. Then, by clicking it, you execute the anonymous function that grabs the testId, calls your service, and handles the data response in a success callback.
Hope that gets you started in the right direction!
EDIT: Added backend webforms "service" exposure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestService(string id)
{
var string = DBCollection.FirstOrDefault(x => x.id == id); // Or whatever you want to return the data
return "You called me on " + DateTime.Now.ToString() + "with " + string;
}
}
This would allow you to call the "WebMethod exposed on your page. For more help with this, please see the following link.
http://www.tugberkugurlu.com/archive/asp-net-web-forms---calling-web-service-page-methods-using-jquery
EDIT: Additional Considerations when performing this type of approach in webforms.
Calling a webmethod with jquery in asp.net webforms
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!
i can write methods like that
public void CompareEmail()
{
some code
}
public void UpdateEmail()
{
some code
}
public void InsertEmail()
{
some code
}
i am click the button onclientclick call the function like that
<asp:Button ID="btnSendNow" runat="server" CssClass="invdisp_btn" OnClick="btnSendNow_Click"
Text="Send Now" OnClientClick="return getEmailMessage()" />
java script function is like that
<script type="text/javascript" language="javascript">
function getEmailMessage()
{
var LoginID = document.getElementById('hdn').value;\\ i can pass 1 or 0
if (LoginID != 0)
{
//This place using CompareEmail() method How to write code comapare values not matching ask update confirm box
var ans;
ans = window.confirm('DO u want to update?');
if (ans == true)
{
// control.UpdateEmail();\\how to call UpdateMethod in .cs file
alert('updated');
}
else {
return false;
}
}
else {
var ans;
ans = window.confirm('DO u want to Insert values?');
if (ans == true)
{
PageMethods.InsertEmail();\\how to call InsertMethod in .cs file
// control.InsertEmail();
alert('Inserted');
}
else
{
return false;
}
}
}
</script>
how to write the code in java script function call the .cs file methods pls help me
Thank u
hemanth
You can achieve it by declaring your method as Web Methods in the code behind files.
Have look at this How to call a server-side method from client-side JavaScript !, it completely gives a solution to your problem.
Otherwise you can also use AJAx to do this.
You should try Pagemethods and ASP.net Ajax.
To call a server side method from client side, you have the following options:
Use ICallBackEventHandler
Use a Webservice with [ScriptService] attribute and call it's web methods from js
Use PageMethods. But that allows you to call static methods on your aspx page, only. Hence you won't be able to access any page controls.
I would recommend option 2, since it's the easiest.