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>
Related
I have a website that uses a ReportViewer to display a SSRS serverside report. I also have controls/textboxes that are used to update the data behind using jQuery/AJAX. I want to try to avoid any page reloads.
I am now trying to refresh the ReportViewer after I have updated my data, without having the page reloaded. Unfortunately, I don't understand if there is a way to (re)load the new data into the ReportViewer. Using the refreshReport method in the ReportViewer control only rerenders with the old data.
Data gets updated with this code, the ReportViewer / report refreshes, but with the old data.
Can I get the new data from the database into the report without having some kind of page reload?
<script type="text/javascript">
function SaveData() {
var data = { text: $('#textBox').val() }
$.ajax({
type: "POST",
url: "ajax.aspx/SaveData",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
}
});
}
function OnSuccess(response) {
var clientViewer = $find("MainReportViewer");
if (clientViewer) {
clientViewer.refreshReport();
}
}
</script>
<rsweb:ReportViewer ID="MainReportViewer" runat="server" ProcessingMode="Remote" Width="100%" Height="100%" AsyncRendering="False" SizeToReportContent="True" ShowToolBar="False" ShowParameterPrompts="False">
<ServerReport ReportPath="/Rep/Rep" ReportServerUrl="http://localhost/reportserver" />
</rsweb:ReportViewer>
<button id="SaveButton" name="SaveButton" type="button" onclick="SaveData()" class="ui-button ui-widget ui-corner-all ui-button-icon-only"><span class="ui-icon ui-icon-disk"></span> </button>
Follow the below steps to make it work:
Use The Timer like ASP.net Timer and JavaScript Timer
refresh Data From Database every Tick and Use Tick Event
the Elapse Time Out then Your Data Reload withOut Page Refresh
Dude these steps definitely work.
any queries please ask in comments.
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";
}
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.
I'm trying to submit a form using AJAX to stop the browser from refreshing the page.
The form is located inside a secondary page, that is called into the main page div ( similar to using a master page and the content placeholder ).
I have been trying several methods but I always reach the same problem. Whenever I try to submit the form, the response is the secondary page with the form, and I can't place the awnser inside the content div of the mainpage like intended.
Any tips on how to make this work?
Main Page
<div id="content"> Secondary page content goes in here loaded using AJAX</div>
Secondary Page
<form runat="server" id="formuser">
<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
Submit Form
</form>
What I intend to do is Submit the above form, while staying in the Main Page and showing the response in the content div.
I need the form to be runat="server" so I can manipulate the data using the code-behind.
Use some jquery:
$('#SaveFormButton').click(function (e) {
$.ajax({
type: "POST",
url: $('#FormToSubmit').attr("action"),
data: $('#FormToSubmit').serialize(),
success: function (data) {
//Whatever you want to do after the form has posted
},
error: function(data){
alert("Error");
}
});
});
Something like this should do it. This way using e.preventDefault() you can use standard form markup and submit buttons.
http://jsfiddle.net/CcDPx/1/
It seems that the method I was using for the content load was building a xmlHttpRquest and it was conflicting with the response that I got from the jquery.
I have a ModalPopup that will contain a gridview and 4 fields to enter items into the gridview itself.
Is it possible to postback to the server and update the gridview while keeping the modal open?
When you submit the fields and the postback occurs the modal closes has anyone done this before? Someone mentioned a solution using jQuery, but this was long ago.
Wrapping the popup's content (i.e. not the popup itself!) in an UpdatePanel worked for me.
My popup content is a search panel with sortable/pageable grid of results. The UpdatePanel gave me the exact behaviour I require with no additional code.
Thanks to Patel Shailesh for the idea.
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<!-- popup content -->
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<ajax:ModalPopupExtender runat="server" ID="PopupExtender" PopupControlID="PopupPanel"
TargetControlID="PopupButton" />
<asp:Button runat="server" ID="PopupButton" Text="Popup" />
The key to doing this is going to be using AJAX of some flavor -- Microsoft.Ajax or jQuery Ajax. If the UpdatePanel is not working, then I'd suggest using jQuery to submit back to the server using AJAX. This would involve creating a WebMethod to accept the AJAX post on the server side and instrumenting the client-side with jQuery to send the request/receive the response. Without seeing your HTML it's a little hard to be very specific.
Basic idea:
$(function() {
$('#modalSubmitButton').click( function() {
$.ajax({
url: 'path-to-your-web-method',
dataType: 'json', // or html, xml, ...
data: function() {
var values = {};
values['field1'] = $('#field1ID').val();
...
values['field4'] = $('#field4ID').val();
return values;
},
success: function(data,status) {
... update page based on returned information...
}
... error handling, etc. ...
});
return false; // stop any default action from the button clicked
});
});
I am not sure if this would work, but try to put whatever inside the modalpopup in a UpdatePanel
Please if this works don't hate me after you release, I hate updatepanels too
A kind of ugly option is to force a postback when showing the modal popup in the first place and setting a ViewState["ModelPopupOn"] = true; and then check that on page load and finally postback again and set it to false/remove it from viewstate when closing the popup.
(these kind of issues are why I hate the ajax toolkit)
I was experimenting with the modalpopupextender, and find a ugly solution.
If the modal panel has a button that makes the postback to happen
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
<asp:Button ID="OkButton" runat="server" Text="OK" OnClick="OkBtn_Click" />
</asp:Panel>
If the OkBtn_Click in the code-behind has a call to:
System.Web.HttpContext.Current.Response.Write("<script></script>");
Then the modalpopupextender is not closed.
This happened too to this guy:
http://forums.asp.net/t/1591860.aspx