How to handle events of HTML elements in DJANGO - asp.net

Need to know how handle ontextchanged /onChange events of HTML elements in DJANGO.
Like in ASP.NET we would simply call a server side function which needs to be executed whea an event is triggered.
for e.g
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
ontextchanged="TextBox1_TextChanged**"></asp:TextBox>
Is there a similar way in DJANGO to hadle these events?

No, there is no equivalent in Django framework. You have to write your own Javascript code to detect changes and then send an AJAX request. It can be easily handled with jQuery library.
E.g :
$('#TextBox1').change(function() {
alert('input value changed : ' + $(this).val());
$.ajax({
url: "yourserver.com/path/", // endpoint
type : "POST", // HTTP method
data: $(this).val() // data sent
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="TextBox1" type="text" value="stack overflow" />
Read .change() and Jquery.ajax() documentation for more information

Related

Passing parameter to telerik popup

Is there any way to pass parameter to telerik similar to window.showModalDialog
The way we call the window.showModalDialog:
window.showModalDialog(pageName, MyArgs, 'status:no;dialogHide=true;help:no')
MyArgs is the parameter we are passing to the popup
Try likes this ,
<script type="text/javascript">
function openRadWin(MyArgs) {
radopen("yourPageName.aspx?Parameter=" + MyArgs , "RadWindow1");
}
</script>
<telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="true"
VisibleStatusbar="false">
<Windows>
<telerik:RadWindow ID="RadWindow1" runat="server" ShowContentDuringLoad="false" Width="400px"
Height="400px" Title="Telerik RadWindow" Behaviors="Default">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
And , at the Page_Load of yourPageName.aspx , get your passed parameter value using Request.QueryString["Parameter"] .
This help article from Telerik shows a way to do it: http://www.telerik.com/help/aspnet-ajax/window-programming-using-radwindow-as-dialog.html. It uses a JavaScript object to put the needed data in a custom field in the control's object, which is then accessed by the content page. Of course, you could, alternatively, use a session/cache object on the server.
This demo is also similar: http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandwindow/defaultcs.aspx?product=window. Note how parameters are added from the code-behind to the JS function the links execute.
On passing more parameters to radopen() - see this help article: http://www.telerik.com/help/aspnet-ajax/window-programming-opening.html. Then you can use the control's client-side API: http://www.telerik.com/help/aspnet-ajax/window-programming-radwindow-methods.html.
You can make it modal with the set_modal() method, or through its Modal server property: http://demos.telerik.com/aspnet-ajax/window/examples/modalpopup/defaultcs.aspx.

ASP.NET TextBox's OnTextChanged server event should fire some client code before going to server

My UserControl has a TextBox, that is subscribed to OnTextChanged event. However, since a lots of business logic and integrations happens on server, I want to disable a form while postback is being performed with some client-side javascript and I'm not sure how to achieve it the right way.
Can I solve this with ClientScriptManager.GetPostBackEventReference?
Edit: as my question seems to be misunderstood:
TextBox is subscribed to event OnTextChanged="tb_TextChanged" which will result on client in onchange=__doPostBack('tb') so I want to inject my javascript disableForm() to onchange DOM event. I know how to implement disableForm(), the question is how to inject my javascript properly?
I would suggest you use the javascript onblur event and check if the field value is changed. If so, you can use jQuery like the below to disable the form elements.
To disable a form element such as a text input or a button (with a made-up id: #elm):
$("#elm").attr("disabled", "disabled");
To enable a disabled form element:
$("#elm").removeAttr("disabled");
You should be able to do this with some simple JavaScript:
<script type="text/javascript">
disableFormFields = function(){
if (document.all || document.getElementById){
for (i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if (el){
el.disabled = true;
}
}
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server" onchange="disableFormFields();" OnTextChanged="TextBox1_TextChanged" />

asp.net link button preventing postback

<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
}
})
});

ASP.NET : Form posting via jQuery

I have an ASP.NET page with 2 ASP.NET text boxes and one ASP.NET drop downlist I want toi use jQuery form posting instead of normal ASP.NET post back.Can anyone guide me how to do this ? How can i access the server side controls in the action page ? I dont want to pass everything via query string. Kindly guide me how to go ahead ? Thanks in advance
you can use simple jQuery selectors to select Server Side Controls suppose you have following textbox on your page:
<asp:TextBox id="userName" runat="server" />
in jQuery you can access it like this:
var valueOfTextBox = $("input[id$='userName']").val();
//OR
var valueOfTextBox = $("input[id$='userName']").attr("value");
if you have few controls on page then this technique is okay but for large forms please use this instead:
var valueOfTextBox = $("#<%= userName.ClientID %>").val();
//OR
var valueOfTextBox = $("#<%= userName.ClientID %>").attr("value");
There is huge performance gain, as explained by Dave here.
You can find more about jQuery selector syntax here.
If you want to post form via jquery AJAX then use this code:
$("#form1").submit(function(){//Where form1 is your form's id
var a=$("input[id$='userName']").val();
var b=$("input[id$='userId']").val();
$.ajax({
type: "POST",
url: "yourPage.aspx",
data: "name=" + a+"&id=" + b,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
More details about jQuery AJAX are here.
You can also use jquery.form plugin to automate the things.

ASP.NET - Ajax requests with jQuery

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.

Resources