I want the click event of a LinkButton in my GridView to not call the grid view's OnRowCommand event.
The reason is because I want to encapsulate this in an UpdatePanel and update ErrorUpdateTextBox without performing a postback.
<asp:GridView ID="DataSourceMappingGridView" runat="server" DataKeyNames="Index" ClientIDMode="Static" OnRowCommand="DataSourceMappingGridView_RowCommand" OnRowDataBound="DataSourceMappingGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="ErrorUpdatePanel" runat="server">
<ContentTemplate>
<asp:LinkButton ID="ErrorTextLinkButton" runat="server" Text='View Errors' OnClick="ErrorTextLinkButton_Click" />
<asp:TextBox ID="ErrorUpdateTextBox" runat="server" Text="">
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If you really want to avoid a post back (UpdatePanels still do a partial post back), then I would recommend capturing the link button's click event client-side and then doing an AJAX call to the server to save/get whatever data is relevant to the link button being clicked, like this:
Remove the OnClick attribute (leave the runat="server" attribute so you can add the ID value to the link button during binding) and add a class attribute to the LinkButton markup to allow jQuery to easily wire up a click event handler, like this:
<asp:LinkButton ID="ErrorTextLinkButton" runat="server" Text='View Errors'
class="error" />
$(document).ready(function() {
$('.error').click(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetError",
data: "{'id':'7'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// Do something error data returned here
}
});
});
});
Finally, create an ASP.NET AJAX Page Method, like this:
[WebMethod]
public static string GetError(int id)
{
// Go and get error data from database or service, etc.
return "Your error message here";
}
Related
I have for example 5 fileupload controls and Also I have a submit button for each of them (in front of each fileupload control) which will upload that fileupload's selected file(s).
But There is a problem, when I click on (for example) second submit button to upload second fileupload's file(s), we will have a post back and other fileupload's file(s) will reset to empty. How can I manage such situation so when the user click on a submit button, the related fileupload's file(s) upload and the other fileupload's file(s) stay in their states. Hope I'm clear enough.
A Picture for better Result:
Disclaimer - this is just modification of great answer here: How can I upload files asynchronously?
And I'm assuming you have jQuery.
<div>
<asp:FileUpload ID="fu1" runat="server" CssClass="fu1" />
<asp:Button ID="btn1" runat="server" OnClientClick="upload(this,'.fu1'); return false" Text="Submit" />
</div>
<div>
<asp:FileUpload ID="fu2" runat="server" CssClass="fu2" />
<asp:Button ID="btn2" runat="server" OnClientClick="upload(this,'.fu2'); return false" Text="Submit" />
</div>
<script type="text/javascript">
function upload(element,selector)
{
var formData = new FormData();
formData.append('image', $(selector)[0].files[0]);
$.ajax({
url: '<%= Page.Form.Action %>', //Server script to process data
type: 'POST',
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
}
</script>
Then within Page_Load:
Page.Form.Attributes["enctype"] = "multipart/form-data";
var file = Request.Files["image"];
if (file != null)
{
// do something with the file
}
I have two textboxes, ID and Name. Based on the combination of these two, my address dropdown should get populated.
I have written an sp to bind items to my dropdown. But the text_changed event of Name textbox causes AutoPostback. I want my dropdownlist to bind automatically when I leave the textbox without causing any refreshing of the page. On page load all 3 should be blank.
Please let me know how to accomplish this using javascript and jquery.
Please excuse for any typing mistakes.
You could either user jQuery Ajax or UpdatePanel
Using JQuery Ajax...
$.ajax({
data: data,
url: "ur url",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
//ur code to bind data to dropdown
}
error: function OnError(result) {
//ur code
}
});
Using Update Panel you can call server side method to bind data to dropdown
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtBox1" OnTextChanged="txtBox1_TextChanged" AutoPostBack="true" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
I have a search form in an updatePanel which retrieves a list of users in a grid in the same UpdatePanel. The name of each user is a commandLink. I want to make the commandLinks as PostBackTriggers.
But when I do it I get an error at the pageLoad time that the controlId does not exist and its true because the grid of users does not render at the load time but through an ajax call.
Any ideas on how can I make the multiple command buttons in a grid retrieved through ajax call as post back triggers?
When adding the items to the grid, within the ItemDataBound event handler, you should register the postback for each specific control (the static identifiers in your HTML declarations are essentially placeholders - not all things repeated in the grid can actually have the same ID). You do this using the ScriptManager.RegisterAsyncPostBackControl method:
The RegisterAsyncPostBackControl method enables you to register Web
server controls as triggers so that they perform an asynchronous
postback instead of a synchronous postback. When the
ChildrenAsTriggers property of an UpdatePanel control is set to true
(which is the default), postback controls inside the UpdatePanel
control are automatically registered as asynchronous postback
controls.
As stated above, using ChildrenAsTriggers is a possibility, too, but this is commonly set to false for more stringent management.
I have found the solution. Here is the code on asp
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
<asp:GridView ID="gvSearchResult" runat="server" OnRowCommand="gvSearchResult_RowCommand"
OnRowDataBound="gvSearchResult_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnDetail" runat="server" CommandArgument='<%# Bind("CNIC") %>' CommandName="Detail">
<asp:Label ID="lblName" Text='<%# Bind("Employee_Name") %>' runat="server</asp:Label>
</asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"Height="25px"Width="30%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Ihad to place OnRowDataBound="gvSearchResult_RowDataBound" on gridView and that function looks like below. So I had to register the iterative control in Scriptmanager as PostBackControl in RowDataBound event of GridView.
protected void gvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnkbtnDetail = (LinkButton)e.Row.FindControl("lnkbtnDetail");
ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkbtnDetail);
}
}
catch (Exception ex)
{
}
}
Kindly help me with a solution to upload a image and display it client side. Simultaneously, I need to save the image in server without refreshing the entire page since, other controls are created dynamically using java script which will disappear when the entire page gets refreshed.
Solution Found:
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5">
<ItemTemplate>
<div id="divImage" runat="server" onclick="Test()" class="draggable">
<asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/MyImages/{0}") %>' runat="server" />
</div>
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/MyImages/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("MyImages"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();
}
You will need to use Ajax for this.
the most trivial solution maybe is using an iframe, containing the form, inside the page . When submitting the form only the iframe will be refreshed and not the whole page
otherwise you could send the base64 representation of your image to your server via ajax. This can be achieved in newer browser, loading the image in a <canvas> element and using toDataURL() method (see Get image data in JavaScript?)
Check out http://www.phpletter.com/Our-Projects/AjaxFileUpload/
You can use ajax to send image(s) you want,
first get the image data :
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
and send it to the server via ajax:
$.ajax({
type: 'POST',
url: 'Save_Picture.aspx/UploadPic',
data: '{ "imageData" : "' + Pic + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("Done, Picture Uploaded.");
}
});
and write a service on the server "Save_Picture.aspx/UploadPic" to read the image data:
byte[] data = Convert.FromBase64String(imageData);
So here we go. I've got two drop down lists on a "customer" record. The first one is called "Store". The second one is called "StoreWarehouse". When the user selects a "Store" value, that filters the "StoreWarehouse" drop down list based on their selection. I have the filtering done via jQuery and AJAX. I am using a ListView and this is in the InsertItemTemplate.
Here's the code for that:
function StoreWarehouseLoad(store_ddl) {
var store_id = store_ddl.options[store_ddl.selectedIndex].value;
var js = JSON.stringify({ store: store_id });
$.ajax({
url: baseUrl + '/AutoComplete/StoreList.asmx/GetStores',
data: js,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var ddl = $("#StoreWarehouse_ddl");
ddl.find('option').remove();
$(data.d).each(function (index) {
ddl.append('<option value="' + this.WarehouseID + '">' + this.WarehouseID + '</option>');
});
switch (culture) {
case "en-CA":
ddl.val(store_id.substring(0, 2) + "I");
break;
case "en-US":
ddl.val('001');
break;
default:
alert("The default warehouse cannot be set because there's something wrong with the current culture...");
break;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
sendErrorEmail(window.location.href, 'Customers.aspx.StoreWarehouseLoad', XMLHttpRequest);
}
});
}
This JavaScript calls a web service that loads the "StoreWarehouse" drop down list based on the selection chosen in the "Store" drop down list. This is all working wonderfully.
My issue is when I save a record. Say I'll be entering in a new record for a customer, enter in all the values (as well as Store and StoreWarehouse drop down lists). I will click "Save" - which is then supposed to save the data to the database. My issue is the SelectedValue from the StoreWarehouse drop down list is not coming through to the business layer. I even captured the e.Values for the "OnInserting" event for the ListView and e.Values["DefaultWarehouseId"] is null. Here's my aspx page for the two drop down lists:
<div class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="StoreId_lbl" runat="server" Text="Branch:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:DropDownList ID="Store_ddl" runat="server" DataSourceID="StoreDataSource" AppendDataBoundItems="true"
onchange="StoreWarehouseLoad(this);" DataValueField="StoreID" DataTextField="StoreID"
CssClass="leftFloat" Font-Size="Smaller" SelectedValue='<%# Bind("StoreID") %>'>
<asp:ListItem />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="StoreId_ddl_rfv" runat="server" ControlToValidate="Store_ddl"
Text="*" ForeColor="Red" />
</div>
</div>
<br class="clear" />
<div class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="StoreWarehouse_lbl" runat="server" Text="Def. Store Warehouse:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:DropDownList ID="StoreWarehouse_ddl" runat="server" CssClass="leftFloat" Font-Size="Smaller"
OnDataBound="StoreWarehouse_ddl_OnDataBound" onchange="changeWarehouse();" SelectedValue='<%# Bind("DefaultWarehouseId") %>'
ClientIDMode="Static">
</asp:DropDownList>
</div>
</div>
As you can see, I've got the "SelectedValue" on the StoreWarehouse drop down list set to <%# Bind("DefaultwarehouseId")%>. DefaultWarehouseId for some reason is not picking up the value in the drop down list for StoreWarehouse.
The funny thing is I can put the following into my JavaScript that is shown above and it alerts me of the selected value of that drop down list:
alert("store warehouse selected is " + $("#StoreWarehouse_ddl").val());
Why isn't the server side code picking up this value?
Thanks a bunch!
Mike
Like #shiznit123 said this information is stored in the ControlState. One of the reasons I prefer the MVC framework over WebForms.
However, in your situation I believe you can get around this issue using hidden fields. asp:hidden. You just have to manage the value directly. So when the user selects an item in the Drop Down List update the corresponding hidden field.
I would suspect the problem is because you are populating your DropDownList control client side. When you postback the serverside ignores your javascript generated items because it rebuilds the controls based on the hidden ControlState.
If you want ajax for this sort of thing in WebForms I'd look into the ajax controls provided and just use an update panel.