I'm changing the items in an ASP.NET DropDownList using jquery, but when I submit the form, the SelectedItem property of the DropDownList is null. Any idea how I can modify the list of items in the DropDownList with jquery without causing this error in the code behind?
Here's the way I'm setting up the DropDownList. Initially, it's an empty ASP.NET DropDownList.
var mailType = $("#ContentPlaceHolder1_ddlMailType");
mailType.empty();
mailType.append("<option></option>");
mailType.append("<option value='D'>Direct Mail</option>");
.
.
.
The DropDownList does end up showing the added items after the jquery executes.
Sorry, you cannot use jquery or Javascript to add items to a server-side ASP.NET web forms list control. The contents of the list control are stored in ViewState, and unless you've done something very strange, your jquery is not updating the ViewState. If you have validation enabled, ASP.NET will throw an error if the form post tag/value does not match any of the known values that are stored in ViewState.
If you wish to have listbox with items that are added dynamically on the client side, don't use a server side control. Just type the HTML into the ASP web form directly (don't use the runat=server tag). To read the contents of the control on postback, don't reference the control; instead, use HttpContext.Request.Form["tag name"]. Note that there is no way for your code behind to know what your jquery has added to the list box, as this information is not passed when the browser posts the form-- only the value attribute of the selected item is passed.
For some more related information, see one of my other answers here.
Couple of things you should check. 1) Modify your JavaScript to get the drop down client id dynamically. The client id changes with every post back event.
var mailType = $("<%= ddlMailType.ClientID %>");
mailType.empty();
mailType.append("<option></option>");
mailType.append("<option value='D'>Direct Mail</option>");
Also, 2) If you are binding the original values of the drop down list in code behind make sure you are handling the post back event. Otherwise the drop down will reset to its original value each time there is a post back.
If Not Page.IsPostBack Then
ddlMailType.databind()
End If
your control is declared with no items in the aspx. since nothing is added to the items collection that way and no adding to items is done in page_init or page_load (when IsPostback = false) when a postback occurs to check SelectedItem, the items property of your DropDownList is empty.
you can still get the value from the forms collection Request.Form[MyDDL.UniqueID]
more in depth here.
Why does DropDownList.SelectedValue is relied on viewstate?
Related
I have asp.net drop down list but I want to load previous classic asp page value into index of the drop down list using Java script.
I can able to take the previous page value with use of Java script.but I am unable set into asp drop down index when page is loaded. Drop down list showing only data from data base not from Java script value.
Protected void page_load()
{
this.BindCountrydropdown();
}
Protected void BindCountrydropdown()
{
/*I have written stored procedure to load values using Data adapter and data table*/
this.ddlCountry.DataTextField=“Countryname”;
this.ddlCountry.DataValueField=“CoubtryID”;
this.ddlCountry.Databind();
}
In .aspx page. Java script:
<script>
function loadpreviouspagevalues()
{
document.getElementById(“ddlCountry”).value=window.opener.parent.document.getElementById(“CountryName”).value;
}
</script>
<body onload =“ loadpreviouspagevalues()”>
<asp:DropDownList ID=“ddlCountry” runat =“server”> </asp:DropDownList>
...
Country name should loaded into ddlCountry index values.
First of all, there are multiple errors just in your javascript function.
function loadpreviouspagevalues(){
document // should not be a capital "D"
.getElementById // No Extra "." should go after this
("ddlCountry").value = window.opener.parent.document.getElementById("CountryName").value;
// I am also skeptical about the inverted commas that you have used here. These are not surely correct
}
Change these and test. Also, when dealing with JavaScript, it is crucial to check browser console to see if any error is there and resolve it accordingly.
I see, you are fetching the value from another page, I would suggest you first validate if the value is properly being returned or not. If it is, then there is the syntactical issue that you need to fix in JavaScript.
I am a bit new to mvc razor and building websites (front and backend). The break down is, I need a button that has a value stored in it be sent to the controller/model. Something similar to html boxtextfor. I have tried giving boxtextfor attributes similar to an input submit button, but it doesn't like that. I have tested the button using javascript and it does have the value within each individual button (# of buttons are dynamic based on previous submit).
I have seen posts like this but I am unsure how to add these to my controller or model so my index page can call it. My model is linked to my index page so I guess I could link these methods in my model.
There's no #Html.Button !
(tried this, but it needs to be linked to my model. A simple button doesn't work.)
Looking for a Html.SubmitButton helper that would accept class attributes in MVC3
I currently don't have access to my code in question. The button needs to be an input submit to go to [HTTPPOST]. However, if you need any more information please let me know.
Thank you for your time,
HtmlNooby
I solved it by wrapping a button with the following. This creates binds each individual button with the given item from an array. Kind of acts like a buttonfor if you will.
Foreach item in array{
#using(Html.BeginForm(…)
{
<button class=input value=item>item</button>
}
}
I have a dropdown on my page which I am populating from client side javascript code. The SelectedIndexChanged does not fire. But when I populate my dropdown from code behide (.cs file) the even is fired.
Any idea how to handle SelectedIndexChanged when dropdown is being populated from code behind. I could see that dropdown is getting populated as per my needs. Only SelectedIndexChanged even is not getting fired. Also note that the drop down is inside UpdatePanel. Will that be a reason?
Here is my html, javascript and code behind event:
<asp:DropDownList ID="ddS" runat="server" OnSelectedIndexChanged="ddS_SelectedIndexChanged"
AutoPostBack="True" Style="position: absolute; width: 50%;">
Javascript:
$('#ddS').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
CS
protected void ddS_SelectedIndexChanged(object sender, EventArgs e)
{
}
Any help would be appreciated. Thanks in advance.
Edit
My main reason behind doing this is:
I have used jquery ui js for a popup, it has a multi-select drop down list. Since the button in a popup cannot have a server side event I have used ajax call to a web-method in .cs file. This method will update my tables from the database with the options selected in the multi-select drop down. Once it is done I want to close the popup and populate a drop down based on the options selected in multi-select.
I cannot populate my dropdown from code behind because the web-method is a static method and hence any method called from that method has to be a static method. If I write a static method then I cannot access UI controls(my drop down) from a static method. So I was hoping I can populate it from JS and then trigger my indexchange event for further computation.
The short answer is don't do this. This is not how ASP.NET Server Controls were designed to work and you will end up creating a Rube Goldburg making it work. Details below:
ASP.NET has a security feature (Event Validation) built in to prevent data being posted that was not present in the control after the Render stage of the page life-cycle. If this occurs an ArgumentException will be thrown. You can disable event validation or override Render and stick lots of code in your Page_Load function, but I wouldn't recommend it.
So why does all of this happen? ASP.NET Server controls use ViewState in an attempt to create state like the state in a desktop application (Windows Forms => Web Forms see what they did there). ViewState gets upset if it doesn't know about the <options> you added to the <select>. A few solutions are:
1) Populate the DropDownList on the Server-Side (unless you have a very good reason not to) and let the ASP.NET Framework do what it was intended to do (you may also have to add the EnableViewState=true attribute to the DropDownList control although I believe it is the default). If the DropDownList is in an update panel ViewState is updated form the PartialPostBack triggered by the panel so the ViewState stays happy while you get flicker-free updates.
2) Forget the Server-side code and create and populate the <select> control using JavaScript.
a) You can bind a JavaScript event listener to update a hidden field when the selected item is changed. Then on PostBack you can read the value of the hidden field to get the value of the last selected item.
b) You can bind a JavaScript event listener to run a POST or GET (AJAX Request) when the selection changes if you need to communicate those changes with the server-side code. You never really said what your objective is...
EDIT AFTER QUESTION UPDATE:
There are three ways I can think of:
1) Remove the ASP DropDownList control and make it a regular HTML select control. Give the control a name (use the name attribute not just the id attribute). ex:
<select name='options'></select>
On POST, HttpContext.Current.Request.Form is a NameValueCollection that will contain Key-Value pairs of the POSTed data. you should be able to get the selected items from your select control by using the name you gave the select control:
var options = HttpContent.Current.Request.Form["options"].Split(',');
options will now be a list of the selected values. If you need this to be AJAX enabled (no page refresh) wrap it in an UpdatePanel.
2) Write the selected items to a hidden field and collect the values from the hidden field on POST.
3) Trigger a POST to a Web Method that updates a session object which can then be read from inside your non-static code behind class members/methods. There is an optional attribute for the Web Method decoration that enables session:
[WebMethod(EnableSession = true)]
Generally, you need to make sure that your event handlers (your SelectedIndexChanged) are set after all DOM operations. In your case you append your html element by jQuery's append method. Unfortunately, adding callbacks to that method is not possible.
A settimeout with the timer "1ms" however always puts the function in the settimeout on the bottom of the call stack.
$('#ddS').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
setTimeout(function() {
// set listener here
// e.g. $("#ddS option").change(function(){
// ddS_SelectedIndexChanged()
// });
}, 1);
Scene : I have a ASP.Net 2.0 app that I need to add functionality to. I need to loop through a gridview's items and compare them to another gridview, If they exist in the other, I must pop up a confirm message to increment the qty. I couldnt find alot on ASP 2.0 so i decided to user a hidden asp field to store what i am processing and based on that registering a clientside script to change the hidden field value and then simulate a postback (I have tried _doPostBack()). So whats happening now is I am trying to access the asp button to simulate a click, but the javascript gets a Null instance everytime. Please advise. (For the testing, i try to alert the button instance, which returns null)
ClientScript.RegisterStartupScript(GetType(String), "ConfirmationScript", "if (confirm('This item already exists, Increment the qty?') == true) {alert(document.getElementById('<%=btnAddSpecificLine.ClientID%>'));}", True)
Try your test like this:
ClientScript.RegisterStartupScript(GetType(String), "ConfirmationScript", "if (confirm('This item already exists, Increment the qty?') == true) {alert(document.getElementById('" & btnAddSpecificLine.ClientID & "'));}", True)
Since you generate this code server-side - pass ClientID directly
I am using C# .Net and have nearly completed the coding to use an OnDataBound for a CheckBoxList to check boxes upon form load in a web form. In the Page_Load a List<> is populated that contains the checked values. I then loop through the list in the OnDataBound event to check the appropriate boxes. This all works fine and I can provide additional code if necessary.
Once the form is loaded I can see everything is checked as expected but when I try to submit the form, my validation is indicating that the box is not checked.
My validation is in Javascript and is using the .checked property, i.e. if (cbx.checked) ...
In the code-behind I am using a loop similar to the following to check the values when appropriate:
foreach (ListItem item in cbList.Items)
{
if (Areas.Contains(item.ToString()))
{
item.Selected = true;
}
}
It seems there is a discrepancy between the .Selected and .checked properties or is there something more basic than this?
Thanks for any help!
Is the function performed on submit a server side or client side method?
I think what is happening is that the Web Page is posting back on submit so your JavaScript isn't in the picture until the page has reloaded. I don't think that the JavaScript will do the validation after a server side onSubmitEvent is initiated until the page has reloaded.