So, I'd like to avoid using jquery directly, I want to use Ajax.BeginForm instead. My problem is that I need the ajax part executing upon leaving a textbox field instead of hitting the submit button. Is that possible, or I have to use jquery functions in this case? (If so, where should I start learning about it?)
just put an id tag on your textbox and use:
$( "#textboxID" ).blur(function() {
alert( "Handler for .blur() called." );
});
Related
I have code that when a user wants to page through a GridView, it asks them (using a JavaScript confirm) if they want to save the data from the grid.
So, I'm able to get the confirm to work (with the code-behind saving function), but I'm noticing that it's not firing the OnPageIndexChanging method - which basically defeats the purpose here.
So, to summarize, can JavaScript access the OnPageIndexChanging method?
Thanks a lot
The OnPageIndexChanging event is a server-side event, so it's not surprising that your Javascript handler isn't getting triggered.
I'm not sure if ASP.Net has a "built in" way to do this; but you can do it by attaching your own Javascript listeners. Here is the general approach (I'm using JQuery to make it easier):
Write a JQuery selector that gets all the paging links that you want to confirm.
Add a click listener for each of those links
Make the confirm function the handler for those listeners
So, the code would look something like this:
$("#grid a").each(function () {
$(this).click(function () {
return confirm("really?");
});
});
Notes
Here grid is the ID of the GridView control, so #grid a selects every a tag within my grid.
Using return confirm() returns false if the user does not confirm, which effectively cancels the click event.
I have a form in asp.net webpage which contains 2 drop down lists and a hyperlink + a button.
I want that if user changes an option is dropdowns to change navigate url.
I have done like so:
<asp:DropDownList ID="ddlPackages" AutoPostBack ="true" runat="server"
onselectedindexchanged="ddlPackages_SelectedIndexChanged"></asp:DropDownList>
and then I have the method defined.
The point is that I don't want to make a submit when I change the drop down. Can I do it using only aspx or I have to use javascript?
If I understand you correctly you want to change the href of the hyperlink based on the selected value of the dropdown. You can do this with javascript. Make sure you have AutoPostBack="false" and remove the OnSelectedIndexChanged attribute as well.
To do it using jQuery, use something like this:
<script type="text/javascript>
$(function(){
var $dropdown = $('#<%= ddlPackages.ClientId %>');
$dropdown.change(function(){
//Put logic to decide the link here based on the select value
var newPage = 'page' + $dropdown.val() + '.aspx';
$('#linkId').attr('href', newPage);
});
});
</script>
Edit:
In case you absolutely must have the logic for getting the new url based on the drop down value on the server side, you can turn the method into a Page Method and call it using ajax from the jQuery script above. But you can probably get away with creating the javascript dynamically in the aspx page instead.
I see two options:
1) Wrap the controls in an Update Panel (.NET 3+). Put AutoPostBack=true on the dropdownlist, and define a SelectedIndexChange event for it that changes the hyperlink control's Navigate URL property. When the user changes the dropdown, you're method will fire without the APPEARANCE of a form submission. Downside: there's a slight delay between the dropdown changing and the link changing. If your server is really, really slow, this delay could potentially cause problems (but this is probably unlikely).
2) Use custom JavaScript and do away with your .NET controls completely. This is what I would probably do, assuming you don't need to do anything else with these controls programatically. Your JavaScript function would monitor the dropdown for a SelectedINdexChange and adjust the href attribute of the anchor tag accordingly. Look into jQuery to speed up development if you aren't too familiar with plain JavaScript.
If the control is an ASP:DropDownList, you can use the AutoPostBack="True|False" property to prevent a postback
If you don't want to use the AutoPostBack you have to post the form using jQuery or Javascript
You can add an event on your drop down list onchange and add the code you need to post the form usin jQuery:
$('#formId').submit();
http://api.jquery.com/submit/
If you to want navigate to another Url add the below code at your DropDownList control (make sure AutoPostBack=false)
onchange="window.location.href='yourUrl'"
it would be better put that Javascript on a separate file anyway
I am building a form, where required field validation must have been checked. I am not using asp validator. I am using JQuery validator like
function checkRequiredInputs(){
$("#frmSaleSubmissionInfo").validate({
rules:{
txtFName:{required: true},
txtLName:{required: true},
txtAddress:{required: true},
txtPhone:{required: true}
},
messages:{
txtFName:"Enter Name",
txtLName:"Enter Name",
txtAddress:"Enter Address",
txtPhone:"Enter Phone Number"
}
});
This is my client side validation. I am using c# in my code behind page. Now if I turned off allowjavascript option in my browser, as far as I know it won't allow javascript. So I am also doing server-side validation for required field. But, since ASP.NET does not have a message-box control, I am having trouble to let the user know what field he is keeping empty. Is there any way to use a control like the message box to show or let the user know what field(s) is/are required to fill the form successfully?
In my point of view, the best fitted to your requirement is using ASP.NET AJAX Toolkit ValidatorCallout control, which can help you to build such solution more fast way.
But if you don't want mixed up two javascript framework (ASP.NET AJAX and jQuery) than you can be expired here, where you can find a solution how to deal with a validation and jQuery.
If you want a modal popup, just send some javascript from the server code:
Response.Write(
"<script type='text/javascript'>alert('A required field is missing.');</script>");
alert() is a javascript function. Response.Write() adds the <script> element to the end of the HTTP response (i.e., the rendered HTML page).
A more elegant approach would be to use the ClientScriptManager to register a startup script:
protected void Page_Load(object sender, EventArgs e) {
this.ClientScript.RegisterClientScriptBlock(this.GetType(),
"RequiredFieldValidationScript",
"alert('A required field is missing.');",
true);
}
The javascript code alert('A required field is missing.'); will be executed after the postback.
See also: https://web.archive.org/web/20210417085026/https://www.4guysfromrolla.com/articles/021104-1.2.aspx
Without javascript, I can't imagine a simple way of recreating a modal type popup. You would have to go as to postback and re-render the page with a DIV blocking out the page and another div on top of it with the errors.
You can always pipe out the errors to a tag next to the submit button and call it a day though.
I have a web flow (asp.net) which has a drop down and a check box.
When the check box is ticked, I need to disable some fields in that form.
When a specific value is selected from the check box, I need to disable other fields.
I specify the checkbox like this:
<%=Html.CheckBox("IsResponseUnavailable", Model.IsResponseUnavailable)%>
And the drop down like this:
<%= Html.MyDropDownList(string.Format("Questions[{0}].Answer", i), (IEnumerable<SelectListItem>)ViewData["Periods"], Model.Questions[i].Answer)%>
Where MyDropDownList is an extension of Html.DropDownList
I've heard about auto-postback - but unsure how to use it - any advice would be great!
I'm using ASP.NET MVC 3.
Thanks!
- L
<%= Html.CheckBox("IsResponseUnavailable", Model.IsResponseUnavailable,
new { onClick = "this.form.submit();" }) %>
<%= Html.MyDropDownList(string.Format("Questions[{0}].Answer", i),
(IEnumerable<SelectListItem>)ViewData["Periods"], Model.Questions[i].Answer),
new { onchange = "this.form.submit();" }) %>
It depends on what you want. Do you want a postback to the server where the server will redraw the view with the correct changes? Or do you want javascript to run when the box is ticked so that the correct fields are changed? Javascript is much smoother and easier to do. There really isn't a way to do an auto-postback without some javascript. Dennis' answer is as basic as it gets and it still uses javascript.
It sounds like you might be better off with webforms instead of MVC if you are doing most of your logic during postbacks. Otherwise I'd try to enrich your UI a bit with some JQuery and take advantage of MVC since you're using it.
You could just do this client side using a bit of jQuery something like
$('#IsResponseUnavailable').change(function() {
if ($(this).has('[checked]')) {
$('#idOfElement').attr('disabled', 'disabled');
}
else {
$('#idOfElement').removeAttr('disabled');
}
});
If you was trying to re-render the HTML for server side then you could take a look at the jQuery load() function
You can also auto submit a form with jQuery using this method but I don't think that's what you want to do.
I have a button called btnSubmit where i set the Form action attribute to a URL like so.
Protected Sub btnSubmit_Click(ByVa....
Form.Attributes.Add("action", "http://now.eloqua.com/e/f2.aspx")
End Sub
This does work but for some reason it only works after I clicked the button the second time. Why is this and how can i fix this?
I am using ASP.NET 3.5 with VB.NET(C# code is also fine)
What I actually want to do it do some code on the submit and then as soons as everything is complete, then set the form action attribute where it must send the form data to another location at that URL.
Thanks in advance!
Fabian is right.
Your code executes on the serverside, after the first submit.
To do what you want, you'll need to emit some javascript using the scriptmanager, which executes in the client, since it will all have to happen before the submit happens in the first place.
Use Page.ClientScript.RegisterClientScriptBlock() to emit a script block with a suitable function which does your stuff, then sets the form's action attribute. Call that function from the button using the OnClientClick attribute.
It doesn't work the first time because the form on which the attributes are added is already rendered.
The first time you click the button, it sets the form attribute, the second time you click it, it's submitting the form that you edited the first time round...
You might want to set the form attribute at some other point in the page lifecycle.
If you need to retain the POST data between pages you might want to use Server.Tranfer. See here for a most excellent explanation: Using asp.net, how do I redirect a user and change the POST data at the same time?