Using asp.net, c# 3.5, vs 2008.
I have an aspx gridview called gv1 with a working c# codebehind onrowcommand method which is called when a button on the row is clicked.
The button on the gridview is being dynamically generated.
I am trying to replace that codebehind call with a javascript function to avoid a roundtrip to the server.
How do I do this?
So far I have tried
adding a row attribute in the code behind when I am dynamically generating the button in a foreach loop , which didnt work:
r.Attributes.Add("OnRowCommand", "javascript:gv1RowCommand(ID);");
the following which gives an error before running: no overloaded method takes 1 arg
<asp:GridView ID="gv1" runat="server" onrowcommand="gv1RowCommand(ID)" ...
various other things such as event onchange , onselected
I am using the follow javascript just to see if I can get it to be called:
function gv1RowCommand(ID) {
alert(
"row command");
}
You need to create object of your button first and then add attributes to it.
check below code -
foreach (GridViewRow row in gv1.Rows)
{
//Creates object of button inside your gridView Row
Button btnRowCommand = (Button)row.FindControl("YourButtonName");
//Adds Attribute to button- in this case adds onclick attribute
//which will fire the
//gv1RowCommand(ID); javascript function
btnRowCommand.Attributes.Add("onclick", "gv1RowCommand('"+ ID +"');");
}
Instead of
// dont use this code
r.Attributes.Add("OnRowCommand", "javascript:gv1RowCommand(ID);");
// dont use this code
This will cause your javascript function gv1RowCommand(ID) to fire when user clicks the button inside the gridview. If you need any more information of using javascript in gridView you can mail or reply. If the above code snippet is not enough for you, you can post much more code listing and will post the proper code accordingly.
Javascript events you can fiddle with:
Javascript Events
You don't have access to any of your page methods or properties in Javascript. You don't have access to anything persistant unless you're workng with Ajax... So there's not a lot that you'd do in RowCommand that you can usefully port to the client javascript layer.
Related
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 want to call a server side method using __DoPostBack, but i don't want a hidden ASP runat server control in my page. Is it possible to call a server side method by its name and not by the name of the control that triggers it?
The problem is, I have an asp button on my aspx page with onclick="ExportButton_Click", and when the button is clicked, it calls the ExportButton_Click codebehind (server side) method. My problem is, I want to get rid of the asp button, because I am trying to create a button dynamically, which when clicked, will do the same thing. Right now, my dynamically created button is calling the doPostBack javascript function which targets the asp Button which triggers ExportButton_Click. So... is it possible to call the ExportButton_Click codebehind method with __doPostBack, without having an asp button? Thanks in advance.
Pass the event target argument in to the __DoPostBack('myEvent') method, like that.
Then in your code-behind Page_Load(), have somewhere code like this:
if (Request.Form["__EVENTTARGET"] == "myEvent")
{
//call your button click function, and pass the button to it (can pass null as the EventArgs)
Button1_Click(Button1, null);
}
These two methods are your server-side friends:
this.Page.ClientScript.GetPostBackEventReference
this.Page.ClientScript.GetPostBackClientHyperlink
They can be used to generate javascript to link to your server side events.
In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.
asp:Button inside SharePoint Dataview Rows with onclick event does not call C# function. Pull it out of Dataview and works fine.
I have a ASP.NET Button I've placed inside a SharePoint DataView's rows with an onclick event pointing to C# function block inside my page. The page refreshes when I click on them, but it's not hitting that code block. If I move the button to outside the dataview and make the ID fixed, the code works beautifully. what's up with that?
the button in the Dataview:
<asp:Button runat="server" Text="Delete" id="Delete{#ID}" CommandArgument="{#FileRef}" OnClick="DeleteDoc"/>
my C# onclick handler (inline C# on the page)
void DeleteDoc(object sender, EventArgs e){sendmail("DeleteDoc");Button b = sender as button;.. more code
This is all inline code and I'm working from SharePoint Designer. Not sure how I can troubleshoot this.
Am I missing something here, maybe I need to add an Itemtemplate or something like we need to in a ASP.NET gridview controls?
Thanks.
IIRc, you need to use Actions, not events.
I need to populate 4 GridViews on an aspx page, but I only bind a datatable to one of them on page load. I need to pupulate the other 3 after page load.
does anyone know the best way to do this using ajax ?
Currently I'm using javascript to __doPostBack on a button that pupulates the 3 GridViews but unfortunately this forces a full page load even when using an update panel. I need the page to load, and then populate the GridViews as the datatables are returned.
any suggestions would be much apreciated.
The way you are doing it should work ok, although using jquery to populate a div via the $("#targetDiv").load("contentUrl"); function may be a cleaner way to do it. Anyway, in order to get your current implementation working, there could be a few things you want to look at:
I assume EnablePartialRendering is true on your ScriptManager (always worth checking!).
Make sure the eventTarget for the __dopostback call is set up as an async trigger for your update panels or that it is inside the UpdatePanel if you are only using one UpdatePanel. (See here for details)
Try returning false from the javascript code that executes in the onclick event handler if you have attached this to a button, to make sure the form is not being submitted normally by your browser when you click the button.
If I understand the question properly, you want the data to load after the page is in the browser. If this is the case, then you can fire an event with JavaScript when the page loads on the client.
One method I've used is to put a hidden (with CSS, not any property) button on the page and 'clicking' it with javascript. The event of the button click event will need to be wired in the page's code. Also the button would have to be in an update panel that either contains the grids you want to be bound or has the appropriate triggers to cause them to reload.
You might look at JQuery to get manage when this code gets fired. The $(document).ready(function(){ /* Your code here... */ }); method will fire after the entire DOM is available, which is faster than waiting on the entire page to load (images and so forth).