I am calling function in codebehind from javascript using webservice.
function GetAdmissionType()
{
InitComponents();
var type="";
type=document.getElementById(dlAdmissionType.id).value;
document.getElementById(hdnAdmissionType.id).value=document.getElementById(dlAdmissionType.id).value;
else if(type=="2")
{
InitComponents();
ViewResettingPanel()
makeFavorite(1);
}
}
function makeFavorite(id) {
PageMethods.SaveInfo(id, CallSuccess, CallFailed);
}
// This will be Called on success
function CallSuccess(res, id) {
alert(destCtrl);
}
// This will be Called on failure
function CallFailed(res) {
alert(res.get_message());
}
Following is my code in codebehind
[System.Web.Services.WebMethod]
public static void SaveInfo(String Id)
{
//to get textbox in form
}
Problem is iam not getting controls in aspx page in SaveInfo.Can anybody help to access controls in form inside saveinfo?
Static page methods cannot get the page's control tree. (They don't receive ViewState)
You will need to use an UpdatePanel.
You can make an asp:Button inside a <div style="display:none> with a regular Click event, make an UpdatePanel triggered by the button, and use Javascript to simulate a click of the button.
Alternatively, you could send the values of the controls that you need as parameters to your page method in Javascript. This will be more efficient than using an UpdatePanel.
You can't.
Your WebMethod is static, meaning it exists once, for all instances of your page class. It has no notion of any individual instance of your Page.
If you need to post your page back, you'll need to actually use postbacks, and not web service calls.
Related
I have a MasterPage website. I'll use the Facebook example to simplify understanding of my purpose.
In default.aspx, i add many DIVs dynamically from code-behind (ie. each div is a SQL result).
In each DIV there's a Label, and also a "Like" HyperLink, listened by a "onclick" JS function that changes "Like" to "Dislike" text in LinkButton and triggers an AJAX call that calls MyMethod(userid, postid) method.
The MyMethod() method changes the Like/Dislike status for the user in SQL.
I want MyMethod() to update the Label too, so MyMethod() would do:
((Label)((Page)HttpContext.Current.Handler).FindControl("lbl_XX")).Text = "foo";
The problem is that i can't get any of the controls of the page.
I also tried a EventHandler added to the LinkButton, but eventually the MyMethod() never gets the Label by FindControl because Page object seems to come without controls.
How can i access the controls of the current page from a method?
I am getting some value from server , if the value is false i need to show alert message on UI without refreshing or postbacking the page.
What i am doing currently is i get the value from server i declare one hidden control and store that value in hidden control and in aspx page i write one JS method to check if that value is false show the alert message, but the problem is i have to do this on click on a button which is present in code behind
so as soon as i click on that button JS code gets executed before i get value from server.
function fnvalidation() {
if (document.getElementById("<%=hdnCtrl.ClientID%>").value == false) {
alert('Please submit it again');
return false;
}
}
On page load i am registering like this :
btnSave.Attributes.Add("onclick", "return fnvalidation()");
C# Code :
bValidate = CommonUtility.ValidateOutput();
hdnCtrl.Value = bValidate.ToString();//Storing value in hidden variable
if(bvalidate == false)
{
//Call javascript method fnvalidation
}
How to call this JS method correctly when value is false coming from server ?
Thanks.
If your page needs to fetch data from the server without refreshing the page, then you need to use AJAX. Which comes down to two things:
Create an AJAX endpoint in server-side code.
Consume that AJAX endpoint from client-side code.
The server-side code likely has several options. HTTP Handlers, empty ASPX pages which clear and response and set a new content type, maybe even Web Methods? It's been a long time since I've used WebForms, so I'm not 100% sure what the recommended approach is right now. But I think Web Methods are what you're looking for. So your code-behind would have something like this:
public partial class MyPage : Page
{
[WebMethod]
public static string GetValue()
{
return "some value";
}
}
Then, assuming you're using jQuery for example, you would call that endpoint from your client-side code:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetValue"
}).done(function (data) {
// respond to the value in "data"
}).error(function () {
// there was an error
});
Now your client-side button click handler can use that, or something like it, to fetch the value from the server. If that's all that button needs to do then don't make it an asp:Button but instead just an input type="button" so that it doesn't post back the whole page. Keeping it as a server-side button would mean canceling the event propagation in JavaScript, which gets ugly with asynchronous operations because there's no immediate way to resume event propagation, you'd have to manually invoke the post back.
I think you can use
Page.ClientScript.RegisterStartupScript
inside your condition if(bvalidate == false) condition like then no need to rely on the value to be set ( i.e in java script function you can remove checking the hidden field value simply alert the user.
Also you can remove this code btnSave.Attributes.Add("onclick", "return fnvalidation()")
Page.ClientScript.RegisterStartupScript(this.GetType(), "validateFnscript", "fnvalidation()",
true);
In my application i am showing a list of records in a grid and each record has a link to update the status of the record. This grid resides inside a user control.
I would like to update the collection when user clicks the link without doing the postback.
Main.aspx
[WebMethod]
public static void UpdateFRStatus(int key)
{
ManagePartnerConfigurationNew pageObj = new ManagePartnerConfigurationNew();
pageObj.UpdateFRStatusforAjax(key);
}
ucFR.ascx
public void UpdateFRStatus(int key)
{
//Code here to update the collection.
}
//Javascript for ajax call
<script>
function statusImageClick(Key) {
//ajax call to update the grid with the updated/inserted data.
$.ajax({
type: "POST",
url: 'Main.aspx/UpdateFRStatus',
data: '{key : "' + Key + '"}',
....
}
</script>
If i move the UpdateFRStatus() to Main.aspx and make it static everything works fine. but i want to keep this method inside the user control to make the code separation.
Can you please suggests me any way i can update the collection without doing the postback.
Thanks in Advance
You Will not get any reference to The Page or usercontrol without doing a postback and loading it back into state.
Pagemethods Works for pages and not usrcontrols.
you could send enough data to The pagemethod to Update The given Entry, (for example key and statusname) then Return data to Update The UI clientside
I don't think there is any way you can directly invoke UpdateFRStatus method of the User Control because it can never be exposed as the entry point for the application.
Though, for maintaining the division of labor and all that stuff, you can keep the static method in Main.aspx. You can do something like following:
[WebMethod]
public static void UpdateFRStatus(int key)
{
ucFRObject.UpdateFRStatus(key);
}
Where ucFRObject is some object of ucFR User control that you have added on Main.aspx.
Which is essentially the same as what you are doing right now.
I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work
Hi i wanted to call a C# function through javascript code.
For Eg: i have C# function which is in aspx.cs page
public void setValue()
{
lblMsg.Text = "hello";
....
.....
}
from javascript i need to call this function.
This is not possible directly indeed. If you are using Web Forms you can have a C# button handler which will change text of your label in server side and then you can call the _doPostBack function for that handler.
Somehow you have to do as postback, either complete or partial. Use AJAX (UpdatePanel)