How to use auto-postback with checkboxes and dropdowns? - c#

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.

Related

Tying it all together - ASP.NET with Bootstrap 3.0

I have an ASP.NET project (non-MVC) and I'm also using Bootstrap 3.0. This is my first time using this combination and need some guidance.
I have a gridview with a buttonfield column. Right now everything is showing up just fine with my gird and Bootstrap table formatting and its binding to my datatable - no problems there.
Next, I want to make the click of the button in the Buttonfield column to initiate a modal window and display a modal based on a unique ID from the row button that opened it.
I don't really know how to tie this all together with ASP.NET and Bootstrap. HTML literals? Dynamic ASP.NET panels? It doesn't matter to me whether there is a postback or not, I'd really just like some guidance or even pseudo-code on how these can be tied together.
Since the OP specifically requested bootstrap help...
You should go through the bootstrap documentation for modals http://getbootstrap.com/javascript/#modals
It makes no difference if you are using MVC or not and you should not need to do any kind of post back to display the modal.
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" />
Will trigger element with id myModal to be shown.
Using bootstrap's own demo code in this jsfiddle demonstrates opening and dismissing the modal.
For the second part of the question, this updated jsfiddle shows how you can also use the button click event to set a value in the modal. You could do other actions in that event handler like get or send data to the backend or change other elements in the modal.
For your case, you would want to handle all button clicks in a single event handler but you can store the id in a custom attribute on the button element. I like to use custom attributes instead of parsing from name, id, or class attributes. This is the bootstrap convention.
$(function() {
$('button.btn').on('click', function() {
var value = $(this).attr('data-value')
$('div.modal').find('#target').text(value);
});
});
Here I have broken out how to get the custom attribute value from the button instance which was clicked.
Post what you have so far and what you still can't get working.
This also shouldn't be tagged with C# or asp.net as that is irrelevant.
You might need a simple js function to take care of that(as mike mentioned this has nothing to do with using or not using bootstrap since it is just some css stuff):
var RunDialog;
$(document).ready(function () {
RunDialog = $("#Id").dialog();
});
You can use ASP.Net Ajax ModalPopup for ASP.Net Web Form. You can google a lot of examples regarding GridView with ModelPopup.
ModalPopupExtender inside a GridView ItemTemplate
I want to make the click of the button in the Buttonfield column to
initiate a modal window and display a modal based on a unique ID from
the row button that opened it.
ModalPopup should work with Bootstrap.

Asynchronous call triggered by leaving textbox

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

How to submit a form without postback in asp.net?

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

How can I use a Modal Pop Up control in ASP.NET similar to a WinForms Message box?

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.

Prevent duplicate postback in ASP.Net (C#)

Simple one here... is there a clean way of preventing a user from double-clicking a button in a web form and thus causing duplicate events to fire?
If I had a comment form for example and the user types in "this is my comment" and clicks submit, the comment is shown below... however if they double-click, triple-click or just go nuts on the keyboard they can cause multiple versions to be posted.
Client-side I could quite easily disable the button onclick - but I prefer server-side solutions to things like this :)
Is there a postback timeout per viewstate that can be set for example?
Thanks
I dont think that you should be loading the server for trivial tasks like these. You could try some thing jquery UI blocking solution like this one. Microsoft Ajax toolkit should also have some control which does the same. I had used it a long time ago, cant seem to recall the control name though.
With jQuery you can make use of the one event.
Another interesting read is this: Build Your ASP.NET Pages on a Richer Bedrock.
Set a session variable when the user enters the page like Session["FormXYZSubmitted"]=false.
When the form is submitted check that variable like
if((bool) Session["FormXYZSubmitted"] == false) {
// save to db
Session["FormXYZSubmitted"] = true;
}
Client side can be tricky if you are using Asp.Net validation.
If you have a master page, put this in the master page:
void IterateThroughControls(Control parent)
{
foreach (Control SelectedButton in parent.Controls)
{
if (SelectedButton is Button)
{
((Button)SelectedButton).Attributes.Add("onclick", " this.disabled = true; " + Page.ClientScript.GetPostBackEventReference(((Button)SelectedButton), null) + ";");
}
if (SelectedButton.Controls.Count > 0)
{
IterateThroughControls(SelectedButton);
}
}
}
Then add this to the master page Page_Load:
IterateThroughControls(this);
I have had the same scenario. The solution of one of my coworkers was to implement a kind of Timer in Javascript, to avoid considering the second click as a click.
Hope that helps,
Disable the button on click, utilize jquery or microsoft ajax toolkit.
Depending on how important this is to you, could create an array of one time GUID's which you remove from the array once the update has been processed (ie posted back in viewstate/hidden field)
If the guid is not in the array on postback, the request is invalid.
Substitute database table for array in a clustered environment.

Categories