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.
Related
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);
I have an application with two sections.
The top section has a dropdownlist that displays all the members in the database using a code behind method on called on page load.
The bottom section has a grid where you can add / delete / edit members using JQuery.
A change in this section obviously does not rebuild the dropdownlist in the top section.
I want to run some code in the JQuery success method that updates/rebuilds the dropdownlist to reflect the newest change to a member. I would like if possible to use the same code behind method that hits the db on page_load to populate the dropdown.
Is this possible? If so, how would I go about accomplishing this?
Any help would be greatly appreciated.
[Requested Code]
.aspx file
<asp:DropDownList ID="director" runat="server"></asp:DropDownList>
jQuery success() fired on add/delete/update member grid.
.aspx.cs (code behind)
private void LoadDirectorOptions(int deptId)
{
var memberRepo = new MemberRepository();
List<Member> members = memberRepo.GetMembers(deptId);
director.DataSource = members;
director.DataTextField = "FullName";
director.DataValueField = "Id";
director.DataBind();
director.Items.Insert(0, new ListItem("<Please Select>", "0"));
}
You can not use the same code behind method since it is a server side code and the JQuery code happens on the client side unless you refresh the page after the JQuery code executed. You can grape all the members on the same web service you are providing for updating the grid.
down list. for example :
$.ajax({
// Updating the grid here and retrun all the members : it will be saved in the response
type: "Get",
url: url,
data: data,
dataType: dataType,
success: success(data)
});
function success(data)
{
//here you can get the resposne from the server
// Iterate through data and add option elements
$(".members").append("<option value=? text=?/>");
}
Most probably your data must be JSON that has all the members in your server members database table. then you can add a CSS class(members) to your drop down list and use JQuery selector to select the drop down list.
Hope this is helpful.
Should use ajax in your success call to call method. http://api.jquery.com/jQuery.ajax/
If you want to refresh the dropdown without refreshing the whole page, you need to wrap them inside an UpdatePanel. When the grid in the bottom section is changed, update the UpdatePanel so that it rebinds the dropdown. To force the UpdatePanel to update in Javascript you could use the GetPostBackEventReference method to force a postback like this:
<%= Page.ClientScript.GetPostBackEventReference(updatePanelID, "")%>
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
Is there any chance, when I select a row from asp:dropdownlist, dynamically change page, execute sql query and after result, change selected row in second asp:dropdownlist?
If this isn't possible only with asp.net and codebehind, please let me know how to execute SELECT-query in javascript (may be with Ajax; but I don't understand it) and change second dropdown's selected row.
Thanks!
Its a bit of a generic question because there is a couple of options that you could do plus I'm not 100% sure what you want to do. In short you could use AJAX to contact a PHP page which will do an operation on your database. A result it generated and sent back to the client. You could use JSON to hold the data that is getting sent to the browser.
All AJAX does is allow you to get data from another location based on the URI you give. I would use the JQuery library as it makes it easy to implement AJAX.
// This will trigger ajax whenever the is a change in the drop down. I am assuming the drop down class is .dropdown
$('.dropdown').change(function() {
$.ajax({
type: "POST",
url: "page_change.php",
data: { name: "about_us" }
dataType:JSON,
success: function(data) {
//The data returned from test.php is loaded in the .result tag
$('.result').html(data.html);
// If you want to change page you would execute
window.location(data.url);
}
});
});
page_change.php will then contact your database and generate JSON.
More information about JQuery AJAX here:
http://api.jquery.com/jQuery.ajax/
You will need to look at JQuery, AJAX, PHP and JSON to change data on your page.
If you just want to change page on a drop down change I suppose you could store the page name in the option id?
$('.dropdown').change(function() {
var page = $(this).attr('id');
window.location(page + ".html");
});
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.