How to reload asp.net GridView after jquery ajax call? - asp.net

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");

Related

how to call a c# webmethod on mouseover of linkbutton in asp.net?

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

ajax request Mootools to asp.net webforms

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.

ajax with page method

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.

Set Server Side OnClick() event Programmatically

I am looking for a way to programmatically set the OnClick event handler for a TableCell object. The ASP equivalent of what I'm trying to do will look like this:
<asp:TableCell OnClick="clickHandler" runat="server">Click Me!</asp:TableCell>
In the above example, "clickHandler" is a server-side function defined in the .cs CodeBehind.
public virtual void clickHandler(object sender, EventArgs args) {...}
However, for my situation, this TableCell object needs to be created dynamically, so setting it in an ASP tag is not an option. I am trying to do something like the following in the CodeBehind:
System.Web.UI.WebControls.TableRow row = new System.Web.UI.WebControls.TableRow();
System.Web.UI.WebControls.TableCell cell = new System.Web.UI.WebControls.TableCell();
cell.Text = "Click Me!";
cell.Attributes.Add("onClick", "clickHandler");
row.Cells.Add(cell);
Unfortunately, in this situation:
cell.Attributes.Add("onClick", "clickHandler");
the "clickHandler" only works as a client-side javascript function. What I'm looking for is a way to link the server-side clickHandler() function, defined in the .cs CodeBehind, to this table cell.
After an afternoon of searching, I have been unable to come up with a working solution. Thanks in advance for any help.
After a lot of work and research, I was able to cobble together a working solution, but it seems like an awful lot of work for something that should already be built-in. What I did was to extend the System.Web.UI.WebControls.TableCell object to include a handle for the OnClick event:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWebApp
{
public class ExpandableTableCell : TableCell, IPostBackEventHandler, INamingContainer
{
private static readonly object click_event = new object();
public ExpandableTableCell()
{
}
// public handles for adding and removing functions to be called on the click event
public event EventHandler Click
{
add
{
Events.AddHandler(click_event, value);
}
remove
{
Events.RemoveHandler(click_event, value);
}
}
// define parent function that will be called when the container is clicked
protected void Click(EventArgs e)
{
EventHandler h = Events[click_event] as EventHandler;
if (h != null)
{
h(this, e);
}
}
// specify the "post back event reference" or id of the click event
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Onclick,
Page.ClientScript.GetPostBackEventReference(this, "custom_click"));
}
// link the custom click id to the click function
void System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
if(eventArgument == "custom_click")
{
this.OnClick(EventArgs.Empty);
}
}
}
}
Here is how I use my new class (almost exactly like the stock TableCell):
System.Web.UI.WebControls.TableRow row = new System.Web.UI.WebControls.TableRow();
ExpandableTableCell click_cell = new ExpandableTableCell();
click_cell.Text = "Click Me!";
click_cell.Click += clickHandler;
// extra little touch for mouseover event
click_cell.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
row.Cells.Add(click_cell);
As I have said, it seems like going through the trouble of extending the class to set the OnClick method in the codebehind is excessive. If anyone has any other ideas or any ways to clean up or legitimize the code above, please let me know.
I don't know if this is relevant to your problem, but I was trying to add a server-side function to a LinkButton and found the following (VB) code: AddHandler cell.Click, AddressOf clickHandler, which worked for me.
According to this code conversion service, this translates to cell.Click += clickHandler; in C#.
Hope this helps!

Is it possible to launch an event from a Silverlight control that can be used in your asp.net page?

Curious how this could be done. Is there any way to create a delegate method within a Silverlight control that can be used within an Asp.net page that the control resides?
For example, let's say you are creating a Silverlight control that solicits information from a user (Ie. Name, age, etc), is there a way to somehow bind to a click event on the Silverlight control from the asp.net page it is sitting on, and then get the information from that Silverlight control?
It is possible to do what you ask, but it doesn't have much to do with ASP.Net. Since Silverlight runs on the client you would just have the click event in Silverlight update the html content. You could then send that data back to the ASP.Net when you do a postback.
Unless you have a good reason to do this, it probably isn't the best approach. You'd probably be better of sending the data back to the webserver using a web service instead of going through ASP.Net.
I done that registering a Javascript event and manually calling back my server controls. Some important pieces below:
<asp:Silverlight runat="server" ID="SilverlightUpload"
Source="~/ClientBin/Silverlight.xap" OnPluginLoaded="pluginLoaded" />
<asp:Button runat="server" OnClientClick="return cancelUpload()" Text="Cancel" />
<script type="text/javascript">
var uploadControl = null;
function pluginLoaded(sender) {
uploadControl = sender.get_element().content.uploadControl;
uploadControl.addEventListener("OnFileListChanged", onFileListChanged);
}
function onFileListChanged(sender, e) {
var files = [];
for (var i = 0; i < e.Files.length; i++) {
files[i] = {
Id : e.Files[i].Id,
Name : e.Files[i].Name
};
}
__doPostBack("<%= RadGrid1.UniqueID %>",
"OnFileListChanged:" + JSON.stringify(files));
}
function cancelUpload() {
$find("<%= SilverlightUpload.ClientID %>")
.get_element().content.uploadControl.StopUpload();
return false;
}
</script>
And Silverlight codebehind:
[ScriptableType] // MUST
public partial class Page : UserControl
{
[ScriptableMember] // MUST
public event EventHandler<FileListChangedEventArgs> OnFileListChanged;
[ScriptableMember] // MUST
public void StopUpload() { }
}
[ScriptableType]
public class FileListChangedEventArgs : EventArgs
{
public FileUploadItem[] Files { get; internal set; }
}
[DataContract]
[ScriptableType]
public class FileUploadItem
{
}

Resources