Refresh GridView from ClientSide (Javascript) in asp.net - c#

I have added the Gridview control on a webPage.
I am deleting any row (one row at a time) by calling PageMethod as follow:
<script type="text/javascript">
function Delete_Row(){
PageMethods.DeleteRow(row_id, GetTimeCallback, ErrorHandler, TimeOutHandler);
}
GetTimeCallback = function (result)
{
if (result) {
alert('Row is deleted');
// I want to refresh the Gridview here
}
}
<script type="text/javascript">
where "row_id" is primery key of the row.
It shows the alert perfectly but does not refresh the Gridview with one less deleted row.
what code should i write to Update the gridview?
NOTE: I dont want to refresh entire page.

Write CallBack Function to acheive this...You can find the Callback Functionality at http://msdn.microsoft.com/en-us/library/ms178208 and http://msdn.microsoft.com/en-us/library/ms178210
Edit:-
protected void Page_Load(object sender, EventArgs e)
{
String cbReference =Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
System.IO.StringWriter strDataGridHtml= new System.IO.StringWriter();
public void RaiseCallbackEvent(String eventArgument)
{
string idToBeDeleted=eventArgument;
//Write deleteCode
//DataBind the Grid
HtmlTextWriter htwObject = new HtmlTextWriter(strDataGridHtml);
GridViewControl.RenderControl(htwObject);
}
public String GetCallbackResult()
{
return strDataGridHtml.ToString();
}
Now as you see this strDataGridHtml will be sent to Javascript Function ReceiveServerData...
<script type="text/ecmascript">
function ReceiveServerData(rValue)
{
document.getElementById("divIDWhichEncapsulategridView").innerHTML = rValue;
}
</script>
Hope this Will Help you..As i don't i have your full code i can't write the exact one...but this should give you some idea on how to proceed...And also please go through the "CallBack" Functionality in order to understand this functionality to the fullest..

Related

Image removing/covering all the controls on the page

So I've got this asp fileupload control which I'm using to select an image. The image is then saved in a temporary folder called "TempImages", then I'm pulling it from there and displaying it on the page, using the code shown below.
protected void Close_Click(object sender, EventArgs e)
{
Div1.Visible = false;
}
#endregion Submit button
protected void LogoToUpload_Click(object sender, EventArgs e)
{
if (upldLogo.HasFile)
{
upldLogo.SaveAs("C:\\TempImages\\" + upldLogo.FileName);
Response.ContentType = "image/jpeg";
string physicalFileName = #"C:\TempImages\" + upldLogo.FileName;
Response.WriteFile(physicalFileName);
}
My problem is that When the image is displayed, it gets rid of all the other controls, i.e. the dropdowns, the textboxs and the labels and all that jazz.
Anyone got any suggestions on how I can make the image just show either in a pop up or just display on the same page but with all the controls still there.
Cheers folks
Ok, so I managed to sort this out by using a little Javascript I put this into the head tag on the controls page.
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=imgLogo.ClientID %>');
var file = document.querySelector('#<%=upldLogo.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
aaaand this into the content.
This served to create a little preview of the picture next to the file upload control once you selected a file.
Cheers!
<input ID="upldLogo" type ="file" onchange="previewFile()" runat="server" />

How to dynamically create and add textbox to a placeholder using AJAX?

I'm trying to create text box dynamically. so I cal it through the AJAX function.
This is my code:
Ajax function
function ChangedAdults(noofAdults) {
alert(noofAdults.value);
$.ajax({
type: 'POST',
dataType: 'json',
url: "/FlightBooking.aspx/Adults",
data: "{noOfAdults:'" + noofAdults.value + "'}",
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#AdultsList").html(result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
code behind
[WebMethod]
public static string Adults(int noOfAdults)
{
FlightBooking obj = new FlightBooking();
obj.CreateAdultsList(noOfAdults);
string test= "";
return test.ToString();
}
private void CreateAdultsList(int noOfAdults)
{
int n = noOfAdults;
for (int i = 0; i < n; i++)
{
TextBox MyTextBox = new TextBox();
MyTextBox.ID = "tb" + "" + i;
AdultsListPlaceholder.Controls.Add(MyTextBox); //error coming here
AdultsListPlaceholder.Controls.Add(new LiteralControl("<br />"));
}
}
But I receive an error:
Object reference not set to an instance of an object
What could cause this problem?
You can not dynamically add controls to a page using JQuery AJAX. Please get a good understanding of asp.net page lifecycle
In short this is how asp.net pages work.
Browswer sends request to server. i.e. http://localhost/test.aspx
Server creates a object for the page class. In this case the class is Test
The object renders the page. That means it converts the Controls of test.aspx to HTML which browsers can understand.
Server sends the rendered HTML back to Browser and destroys the object.
Browser displays the page.
So the server creates a new object every time it receives a page request.
However when a call to WebMethods is made using AJAX, no page object is created. This is why Webmethods have to be static.
I can see you are trying to create a object yourself and add the dynamic controls to that object. But this object is not related to the content displayed in the browser. So, adding controls to this object won't change anything that's displayed in the browser. For that to happen you have to post the whole page back. And if you return the rendered output of the object you created with Response.Write, that will return the HTML version of the whole page. Which is basically same as a PostBack
However, you can achieve AJAX based dynamic control rendering using UpdatePanel. Below is one way to do it
ASPX page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
Hope this helps.
You're mixing your paradigms. What would you expect this code to do? You can render controls in response to an AJAX call, but you must then manually insert the processed HTML into the DOM.
Call server using AJAX
Instantiate a dummy page container
Render server control
Return markup
Insert into DOM
Or, you can add new controls in response to a server event via a full postback or an async postback (e.g. an UpdatePanel).
In asp.net you can not create server control from jQuery or java-script.
Though you can call web-method from jQuery but you can't add any control from web method.
More details
Add new ASP.NEt server controls with jQuery?
One of the idea it to create textbox is to create html textbox
<input type="text" id="text1" ></input>
And post your value through jQuery ajax for manipulation.
Edit 1
Other way is to create all the controls at page load (If you know the maximum number)
Hide them initially
Show one by one on button click
And get the value on the server after postback.
Example:
add text to an asp.net textbox control with jQuery
AdultsListPlaceholder is null, you need to override its onload function to create children of this control.
e.g.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CreateAdultsList(5);
}

How to pass value of C# variable to javascript?

In button click event I am writing this code.(code behind).I know button click event
protected void button_click()
{
string s1 = "Computer";
StringBuilder sb = new StringBuilder();
sb.Append(#"<script language='javascript'>");
sb.Append("document.write('<table><tbody>')";);
sb.Append("document.write('<tr><td>Information</td></tr>')";);
if(s1 == "Computer" )
{
sb.Append("<tr><td>s1</td></tr>");
}
sb.Append("document.write('</tbody></table>')";);
sb.Append(#"</script>");
}
It is working but I want value of s1 not s1.I know javascript is a client side programing.I wrote this function in button click event.How can pass value of s1 that is computer to table's cell
simply
sb.Append("document.write('<tr><td>" + s1 + "</td></tr>');");
Have you tried
if(s1 == "Computer" )
{
sb.Append("<tr><td>"+s1+"</td></tr>");
}
You could change this line to:
sb.Append("<tr><td>" + s1 + "</td></tr>");
Your code is a bit irrelevant to the question you're asking. Your error has already been fixed by previous answers. But I will try to expand the asnwer further. If you wish to pass some value from C# to JavaScript, there're different methods.
1) You could make a protected method in a codebehind file and call it from your .aspx file, like
my.aspx
<script type="text/javascript">
var x = '<%= GetMyValue() %>';
DoFooWithX(x);
</script>
my.aspx.cs
protected string GetMyValue()
{
return "example";
}
2) If you wish to execute some JavaScript once page finishes loading, you could also do it from your codebehind like this
my.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string myScript = string.Format("myVar = '{0}';", GetMyVarValue());
ScriptManager.RegisterStartupScript(this, this.GetType(), "MyVarSetter", myScript, true);
}
private string GetMyVarValue()
{
return "example";
}

How is it possible to load jquery files after a specific update panel has been loaded?

I have set of jquery files.like this :
<script src="js/PortalJs/jquery-ui-personalized-1.6rc2.min.js" type="text/javascript"></script>
<script src="js/PortalJs/inettuts.js" type="text/javascript"></script>
How is it possible to call these files after a specific update panel has been loaded.
To make calls on javascript side after the update panel loaded you use this standard code.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// here you can load your scripts.
}
You can add at the EndRequest a code that loads the javascript, but take care to load it only ones. If the jQuery have conflicts try the jQuery.noConflict() command. http://api.jquery.com/jQuery.noConflict/
Sys.WebForms.PageRequestManager endRequest Event
MSDN Documentation
The endRequest event is raised after an asynchronous postback is finished and control has been returned to the browser. You can use this event to provide a notification to users or to log errors.
Reference - endRequest
Sample Code
<script type="text/javascript" language="javascript">
function EndRequestHandler(sender, args){
// here you can call the function provided by other user
}
<script
So you will have to write down the script loading function in javascript...
Here is a function that I use to add dependencies dynamically
function addDependencies(args) {
var head = document.getElementsByTagName('head')[0];
// todo refactor this logic
function exists(tag, src) {
var elms = document.getElementsByTagName(tag);
for (var i=0; i<elms.length; i++) {
if (elms[i].getAttribute('src') === src) {
return true;
}
}
}
for (var src in args) {
var isCss = /.+\.css$/i.test(src);
var isJs = /.+\.js$/i.test(src);
var tag = isCss ? 'link' : 'script';
if (!exists(tag, src)) {
if (isCss) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
var link = document.createElement(tag);
link.type = 'text/css';
link.href = src;
head.appendChild(link);
}
} else if (isJs) {
var script = document.createElement(tag);
script.type = 'text/javascript';
script.src = src;
script.onload = args[src]();
head.appendChild(script);
}
}
}
}
heres a demo
update panel has an onLoad event: http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.onload.aspx.
<asp:UpdatePanel OnLoad="upOnload" ...
you can load your javascript from the updatePanel Onload event in code behind like this:
protected void upOnload(object sender, EventArgs e)
{
Page.Header.Controls.Add(new LiteralControl("<script type='text/javascript' src='" + Page.ResolveUrl("~/js/PortalJs/inettuts.js") + "'></script>"));
}

How can i determine PostBack value in window.onunload?

In our project we are deleting something after the user left the page. We are using window.unload event for doing this.
window.onunload = function() {
// delete something
}
We are generally using buttons, linkbuttons..etc in UpdatePanel so we hadn't needed to check Page.IsPostBack property.
Today we realized that we used some buttons out of UpdatePanel and this situation had produced some errors. After that we decided to change our method, defined a global variable (var _isPostBack = false), at the top of the our page and:
window.onunload = function() {
if (_isPostBack) {
_isPostBack = false;
return;
}
// delete something
}
Altought i set the g_isPostBack in Page_Load, g_isPostBack didn't change. I tried "RegisterClientScriptBlock", "RegisterOnSubmitStatement" and "RegisterStartupScript" methods. Register methods were called before the onunload event but _isPostBack was set after onunload event had triggered...
if (IsPostBack)
{
Control c = MyClass.GetPostBackControl(this);
bool inUpdatePanel = ControlParentForUpdatePanel(c);
if (!inUpdatePanel)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = true;", true);
}
}
Is there anyone to help me?
that's the trick...
if you add onsubmit attribute to your form tag:
<form id="form1" onsubmit="return yourPostBack()">
and than write your own function:
function yourPostBack()
{
_isPostBack = true;
return true;
}
and finally in the page load:
if (IsPostBack)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = false;", true);
}
with this method you can understand that it is postback or not, in window.onunload
I hope i am on the right track here,
As i understand,
the OnUnload() is ClientSide,
and therefore you don't have the server objects
what you can do... is save the value in a hidden field.
As i am used to PHP you can even embed the value in a Javascript variable
Dont know if this applys to ASP.NET:
<script language="javascript">
var MyServerVariable = "<?PHP echo MyServerVariable ?>"
if(MyServerVariable == "Blah...")
{
}
</script>
translates to
<script language="javascript">
var MyServerVariable = "VALUE"
if(MyServerVariable == "Blah...")
{
}
</script>
But same thing can be done with <asp:Label /> , i am sure...

Categories