I have a gridview inside an updatepanel and I have a javascript that calls a page method using jquery. I'd like the page method to refresh the gridview based on the parameter it receives from the ajax call.
So far, I have the following:
1) in the javascript, there's a function that calls the page method:
function GetNewDate(thedateitem) {
DateString = (valid json date format that works)
$.ajax({
type: "POST",
url: "./CallHistory.aspx/ResetDate",
contentType: "application/json; charset=utf-8",
data: DateString,
dataType: "json",
success: successFn,
error: errorFn
})
};
2) In the aspx page I have:
<asp:UpdatePanel ID="MyPanel" runat="server">
<ContentTemplate>
<asp:GridView ID="MyGrid">
3) In the code behind:
public partial class Pages_CallHistory : System.Web.UI.Page
{
List<ViewCallHistoryModel> TheCallHistory;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TheDate = new DateTime(2011, 1, 13);
LoadCallHistory(TheDate);
MyGrid.Datasource = TheCallHistory;
MyGrid.Databind;
}
}
protected void LoadCallHistory(DateTime TheDate)
{
linq query that fills the variable TheCallHistory
}
[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
var test = new Pages_CallHistory();
var test2 = test.LoadCallHistory(TheNewDate.Date);
//test2 loads fine
test.GridCallHistory.DataSource = test2;
//this is not underlined but bugs at runtime
//Object reference not set to an instance of an object.
test.GridCallHistory.DataBind();
test.MyPanel.Update();
//this is not underlined but doesn't get executed because
//because it stops at the line above
//I'd like to update the content of
//the gridview on the page with the updated gridview.
}
What I'd like to do in the page method is 1) call LoadCallHistory with the new date parameter and 2) tell the gridview MyGrid to rebind with the new data that's in TheCallHistory.
I'm struggling with this page method; it's not working and I'm stuck. How is this done?
ok so the solution is to use _doPostBack in javascript:
__doPostBack('MyPanel', DateString);
The page method is for sending and receiving data only, not for doing postbacks on updatepanels.
Take a look at my answer to this related question here. In short, you create a new instance of the grid and capture its output manually.
Related
Is it possible to call a c# webmethod on mouseover on Linkbutton ? what i want is to call a webmethod in which i am binding a repeater control with datatable. How?
in aspx:
<asp:LinkButton Text='<%#Eval("SNA")%>' ID="lnkpro1" runat="server"
CssClass="linkbutton" servicemethod="GetRecords"
OnClick="btn_Click1" CommandArgument='<%# Eval("Sets") %>'></asp:LinkButton>
in aspx.cs:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public void GetRecords(object sender, EventArgs e)
{
}
I am not getting the point that is how is it possible to call a webmethod on linkbutton mouseover. I have used a webmethod in textbox autocomplete extender but it has a propperty of calling a webmethod but is it so in this case also? Thank you.
Use ASP.NET AJAX Page Methods, like this:
[WebMethod]
public static List<Record> GetRecords()
{
// Go to database to get list of records
List<Record> listOfRecords = GetRecordsFromDatabase();
return listOfRecords;
}
I made up the Record class here. A list of something needs to be returned, so I made it up for the example's sake.
Note: ASP.NET AJAX Page Methods automatically JSON-encode their response, so there is no need for serialization in the page method if you are using JSON on the client-side.
Now you can call the ASP.NET AJAX Page Method, like this:
$(document).ready(function() {
$('.linkbutton').mouseover(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetRecords",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Do something with records returned here
// Use result.d to get to JSON data
}
});
});
});
You can do that using jQuery Ajax method to call a WebMethod:
Refer this for an ultimate example for Calling an ASP.NET C# WebMethod
I was wondering. I tried googling for answers but they don't give me answers. Thanks.
Yes, an ASP.NET AJAX Page Method will continue execution after a user leaves a page, but the result (if any) will not come back to the page, since the page where the request was initiated is now gone.
For example:
Code-behind on Default.aspx page:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetHelloWorld()
{
Thread.Sleep(20000);
return "Hello World";
}
protected void ButtonContactRedirect_OnClick(object sender, EventArgs e)
{
Response.Redirect("Contact.aspx");
}
}
Markup on Default.aspx page:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetHelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
});
</script>
<asp:Button runat="server" ID="ButtonContactRedirect" Text="Go to Contacts Page" OnClick="ButtonContactRedirect_OnClick"/>
So we have a button on Default.aspx that will redirect to another page (Contacts.aspx) when the user clicks it. Meanwhile, when Default.aspx is loaded, there is an AJAX call to the page method that sleeps for 20 seconds before returning the string Hello World.
If you put a break point on the following line:
return "Hello World";
When you run the program and the page loads, if you do not click the button for 20 seconds then the AJAX success callback will fire and an alert will show the string object returned. If you press the button before the 20 second sleep finishes, then the Redirect() will happen and the Contacts.aspx page will load, but the break point will be hit once the sleep finishes; however the returned Hello World string will be lost, because the AJAX context was tied to the Default.aspx page and not the Contacts.aspx page, which is now gone.
I have GridView, textbox, an html button. What it does is the textbox contains a value that will be saved in the database after clicking the html button.
Here is the code for the page:
<div>
<div id="Gridview-container">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input type="button" id="btn" value="insert" />
</div>
</form>
<script type="text/javascript">
$("#btn").click(function () {
var a = $("#TextBox1").val();
$.ajax({
url: 'WebService.asmx/insert',
data: "{ 'name': '" + a + "' }",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function () {
//alert('insert was performed.');
$("#Gridview-container").empty();
}
});
});
</script>
Here is the code behind of that page:
public partial class GridViewCourses : System.Web.UI.Page
{
Database db = new Database();
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = db.LoadCourses();
GridView1.DataBind();
}
}
Here is the code for the webservice:
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public void insert(string name)
{
Database db = new Database();
db.Add(name);
}
}
I want something that has the same effect as GridView.DataBind() so that when I perform delete and update the GridView is reloaded based on the record from the database.
Sir/Ma'am, your answers would be of great help. Thank you++
You could use an UpdatePanel and place the GridView in it. Then in order to raise a post-back from javascript you will have to use the __doPostBack and target your UpdatePanel.
Some information here that should help you implement this: http://encosia.com/easily-refresh-an-updatepanel-using-javascript/
You have to place your GridView inside an update panel & somehow refresh it from clientside. If you want to do everything clientside you can reinvent the wheel & use something like jTables & create your own grid but I will not recommend that
You can do either use __doPostback Javascript
Or place a hidden button field on your page & call its click event on your close button clientside like
document.getElementById('yourButton').click();
you write gridview binding code in separate method. like this
public void dataBind()
{
GridView1.DataSource = db.LoadCourses();
GridView1.DataBind();
}
[WebMethod]
public void insert(string name)
{
Database db = new Database();
db.Add(name);
//after successful insertion call dataBind
dataBind() //this method will update the grdivew with new data
}
define the webmethod as pagemethod in the codebehind if you want.
hope this helps..
I realize its a bit old forum. But, I am using UseSubmitBehavior = false on the button. Ofcourse, making the button an asp:Button. And, declaring Onclick and OnClientClcik events. This way, its gonna first fire onclientclick event and then fires onclick event.
Sri
Add the line below to the end of your jQuery:
$("#YourGridView").load(location.href + " #YourGridView");
I am trying to post a request to the server but it wont hit when I use the debugger?
server:
public partial class _Default : System.Web.UI.Page
{
public string HitThis()
{
return "braza";
}
}
<script type="text/javascript">
var myRequest = new Request({
method: 'post',
url: '/Default.aspx/HitThis',
onSuccess: function () {
alert('good');
},
onFailure: function () {
alert('nope');
}
});
myRequest.send();
</script>
If you want to be able to call your HitThis method, you need to make that method, static, decorate it with the Web Method attribute and enable Page Methods on your ScriptManager
Example:
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
[WebMethod]
public static string HitThis()
{
return "Hello World";
}
You need to first understand how ASP.NET AJAX Script Services or PageMethod works! Page Methods has to be decorated with the WebMethod attribute and needs to be static.
[WebMethod]
public static string HitThis()
{
}
See this article that illustrates calling page method using jquery. You can adopt it with mootools. However, note that page methods needs content type to be JSON data and response will also be in JSON.
Perhaps you can write your own wiring logic in the ASP.NET page using Request.PathInfo if you want to use normal form posting. For example,
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.PathInfo == "HitThis")
{
HitThis();
}
}
In your method, you need to work with Response (HttpResponse) and after modifying the response, you need to end it (HttpResponse.End) so that normal page processing would not happen. If your method needs parameters then you have to pass them via form data and/or query string.
i am a beginner
function PopupUserRegist() {
result = $.ajax({ url: "Default.aspx?cmd=Setting",
async: false ,
complete: function () {
// unblock when remote call returns
}
}).responseText; ;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request["cmd"] == "Setting")
{
div.InnerText = "test"; //This does not change inner text
}
}
protected void Button2_Click(object sender, EventArgs e)
{
div.InnerText = "test";//This change inner text
}
when call PopupUserRegist(); does not change?
You've got confused about the flow of control with ASP.NET.
Page_Load() occurs on the server side at page generation time and can change the data that is about to be sent back in the HTML page to the browser.
When you call the ASPX again through ajax() from JavaScript, the codebehind can't directly touch the page content, because that's already sitting over on the browser. If you want to change the data in the page, you'll have to have the ASPX return a plain value to the JavaScript code in the responseText:
$('#myDiv').text(
$.ajax({
url: 'Default.aspx?cmd=Setting',
async: false
}).responseText
);
or, better, avoiding the unpleasant use of synchronous xmlhttprequest:
$.get('Default.aspx?cmd=Setting', function(result) {
$('#myDiv').text(result);
});
If you really want to blur the line between code that runs on the client and server sides, look at using runat="server", click events, postbacks and viewstates.
Check if the condition is met.