I've got this textBox which triggers off an ajax request using jQuery:
<asp:TextBox ID="postcodeTextBox" runat="server" Text='<%# Bind("POSTAL_ZIP_CODE") %>'>
$(document).ready(PageLoad);
function PageLoad() {
$(container + 'parentProjectTextBox').change(GetProjectName);
}
function GetProjectName() {
var projectNumber = $(this).val();
if (projectNumber == '') return;
$(container + 'parentProjectPanel').block({ message: '<img src="../Resources/RadControls/Ajax/Skins/Default/loading7.gif" />' });
$.ajax({
type: 'POST',
url: projectMasterWebServicesUrl + 'GetProjectName',
data: "{'projectNumber':'" + projectNumber + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: GetProjectNameOnSuccess,
error: GetProjectNameOnError
});
}
This ajax request gets a list to populate this dropdown:
<asp:DropDownList ID="cityDropDownList" runat="server" OnDataBound="cityDropDownList_DataBound">
<asp:ListItem Text="...Select..." Value="0">
</asp:ListItem>
</asp:DropDownList>
Everything works fine. The only problem I'm having is that when I update my formView priod to saving that record I can't see the value that was set to that dropdown. As I'm populating this dropdown in the client side I supose ASP.NET loses track of that ....
Does anyone have any insights?
Apparently when I switch on/off the EnableEventValidation property for that page I sometimes get the correct value.....
Thanks !
You should create a hidden field store that value. Update that HiddenField in your Javascript and then read it on the server side. Also, if you have EventValidation=true and you change the items in the dropdown list you will get well known exceptions.
This may not be the problem...but are you checking for Page.IsPostBack in your Page_Load?
I've made that mistake way too many times.
If you are loading that drop down control from the Page_Load, and you are not checking
if (!Page.IsPostback)
you will reload the control. Then when you get the value from the drop down...the value is gone because you reloaded the dropdown.
Related
I want to make a password recovery function where the users needs to enter the mail adress.
The mail adress has to be validated by asp.net. I dont want the site to refresh after reseting password. Thats why I disabled autopostback for my button. The problem is that disabling the autopostback also stopped the validation of the input.
I dont want to use javascript to validate the input.
So is it possible to disable autopostback but keep the validation behaviour?
Thanks alot!
This is my asp.net code:
<asp:Label>Email: </asp:Label><asp:TextBox id="emailTextbox" TextMode="Email" runat="server" CSSClass="emailTextbox"/>
<asp:Button Text="Anfordern" runat="server" CSSClass="ResetPassword" CausesValidation="True"/>
and this is the called ajax behind the button
function ResetPassword() {
alert($("#<%=emailTextbox.ClientID%>")[0].value);
$.ajax({
type: "POST",
url: "/pages/passwordRecovery.aspx/ResetPassword",
data: '{mail: "' + $("#<%=emailTextbox.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
//alert(response.d);
}
});
}
I'm trying to change a label text from cs file after I receive a message from the server.
I tried using to put the label in updatepanel but couldn't make it work.
How can i update the display of the label?
Usually this is something along the lines of
myLabel.Text = "Value";
If it's in an UpdatePanel, the rules are a little different. I think you need to get the control, then update its value. Something along the lines of:
Label lbl = (Label) updatePanel1.FindControl("myLabel");
lbl.Text = "Value";
If you are trying to avoid a post back, then you can use ASP.NET AJAX Page Methods to query the server via AJAX and then push the value returned into the label control, like this:
Markup:
<script type="text/javascript">
$(document).ready(function () {
$('.TheButton').click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.TheLabel').text(data.d);
}
});
return false;
});
});
</script>
<asp:Label ID="Label1" runat="server" Text="Nothing" CssClass="TheLabel" />
<br/>
<asp:Button runat="server" ID="Button1" CssClass="TheButton" Text="Update Label"/>
Code-behind:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
Note: ASP.NET AJAX Page Methods are static methods that are not part of the ASP.NET page life-cycle. They do not have access to any of the controls on the page, but are very useful for getting data from the server (in this case the server time). In the interest of simplicity, I used CSS class names on the server controls to make the jQuery selectors simpler.
<asp:LinkButton ID="lbnImages" runat="server" CssClass="link"
PostBackUrl="AddImage.aspx" CausesValidation="True"
ValidationGroup="Save">Images</asp:LinkButton>
<asp:CustomValidator ID="cstval" runat="server" ControlToValidate="txtName"
ValidationGroup="Save" ErrorMessage ="Duplicate name"
OnServerValidate="Project_validation" />
I am checking for duplicates using the custom validator (server side code)
If the server side custom validator shows error the link button must not redirect to the page.
I need to stop the post back when the validator fires.
If you want to prevent the postback, you should do the validation client side by adding a custom javascript validation function to your validator control. This is described in this blog post.
If your validation logic can only run on the server, you will have to let the postback happen, but wrap all the code that you want not to run in e.g. an
if (Page.IsValid) { ... }
I see you are checking for duplicates, the only way to validate it without causing a postback is to make an ajax call.
Make a call to some service that will check if it's a duplicate or not, then if it's not valid stop it. Using jQuery syntax:
$("save_button").click(function(e){
$.ajax({
async: false, // will finish this request before executing anything else
url: "validation_page",
type: "POST",
data: ({name: "value from a field"}),
success: function(msg){
if (msg != "ERROR") // whatever msg is not valid
e.preventDefault(); // will not do the postback
}
})
});
I want to update my dropdown list datasource (get the values from the database again) but i want to do that from jQuery, there i insert/update/delete records from that same database table.
This is my dropdown list
<asp:DropDownList ID="ddl" runat="server"
AppendDataBoundItems="True"
DataSourceID="ShortCodeDataSource"
DataTextField="ShortcodeId"
DataValueField="ShortcodeId">
<asp:ListItem>Select one...</asp:ListItem>
</asp:DropDownList>
<asp:ObjectDataSource ID="ShortCodeDataSource" runat="server"
SelectMethod="GetAllShortcodes"
TypeName="Sod.Iris.Service.ShortcodeService">
</asp:ObjectDataSource>
Also, beside code that a432511 posted, you can use UpdatePanel approach.
Put your dropdown in a UpdatePanel and then just call refresh from jquery.
On this link you have example how to do this:
http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript/
cheers
You need a ScriptManager with EnablePageMethods = true
Then you need a method in your page's codebehind that is decorated with [WebMethod]. That method will be responsible for the call to the database
[WebMethod]
public string GetNewData()
{
// Get Data
// maybe serialize and return
}
Then your jQuery needs to looks something like this:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetNewData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, msg) {
// Do something with data
}
});
The success callback will need to process the returned data and manually populate the control's drop down list. The other option would be to get that serialized data from a Web Service (asmx). It would function much the same.
Hope that helps!
I am getting a JSON object from a webMethod by the call below and I set some textBox values based on the returned objects attributes.
Problem is, just for a moment my textBoxes are populated but then immidiately they return back to empty.
Do I make a mistake or I cannot make DOM elements modifications within a success function?
Thanks.
var ajaxCallOptions = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JQuery/Chapter16-AJAX/PersonWebServices.asmx/GetPerson",
context: document.body,
data: JSONObject,
dataType: "json",
success: function(data, textStatus, XMLHttpRequest){
var myPerson = data;
jQuery("#"+"<%=txtFirstName.ClientID %>").val(myPerson.d.FirstName);
jQuery("#"+"<%=txtLastName.ClientID %>").val(myPerson.d.LastName);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('Error: '+textStatus);
} };
jQuery.ajax(ajaxCallOptions);
The returned data is:
Additional Note:
{"d":{"__type":"BusinessObjects.Person","FirstName":"Burak","Id":"001","LastName":"Ozdogan","Department":"Information Technologies"}}
and this is a function which is bound to click event in the form:
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="loadPerson($('.personId'));"/>
If your $.ajax() is fired via a submit the default behavior is likely happening, and reloading the page.
Use return false; or event.preventDefault() at the end of your submit handler if that is the case.
$('.mySubmitButton').submit(function() {
// Send ajax request
return false;
});
or:
$('.mySubmitButton').submit(function( event ) {
event.preventDefault()
// Send ajax request
});
This same technique is used for links created from <a href=''> elements when you want to prevent the default behavior, or for any other element that has a default behavior for that matter.
I suggest use of FireBug or similar to examine the content being returned by the AJAX call. Failing this, try alerting the data which is returned.
Is the data returned the expected data?
Thanks Patrick.
It worked after this modification:
<asp:Button ID="btnSearch" runat="server" Text="Search"
OnClientClick="loadPerson($('.personId'), event); return false;"/>