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.
Related
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?
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);
How can I get the value of my bean to display from my javascript file?
My bean - dBean.strIssueDate
In the $(document).ready(function() of my jsp, I set the following:
$('#content').data("strIssueDate", "<c:out value="${dBean.strIssueDate}"/>");
My problem is that the date is updated (and it's correctly updated in the database), but I would like to call the value from the javascript file.
The update begins with a checkbox on another jsp page, which updates the data value via a java file, and then triggers the function in the javascript file, which is where my alert is called.
My (incorrect) code in the javascript file (which is not between tags, but just a file consisting of only js:
alert("${dBean.strIssueDate}");
which shows on the alert as ${dBean.strIssueDate}
I've tried removing the double quotes, substituting for single quotes, swapping the $ for a #, but nothing seems to work.
Looks like you are using JQuery and have already set the date on the #content so what about this.
alert($("#content").data("strIssueDate"));
I have a page in my site that has 5 different textboxes to add different things to my database. I would like each one to be able to have a success code tied to it, but also be able to refresh the page. I use Response.Write("<script>alert(" & "'Image Title added successfully'" & ")</script>") to show the message, but when I add Response.Redirect("AddToPicklist.aspx") to it, the success message doesn't display anymore. Is there an easier way to do this is ASP.net?
<tr><td class="title">Image</td></tr>
<tr><td>Image Title: </td></tr>
<tr><td><asp:TextBox ID="txtImageTitle" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="btnSubmitImage" runat="server" Text="Submit" /></td></tr>
</table><br />
Protected Sub btnSubmitImage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmitImage.Click
**insert code is here but it's not relevant so I'm omitting it**
Response.Write("<script>alert(" & "'Image Title added successfully'" & ")</script>")
Response.Redirect("AddToPicklist.aspx")
You are redirecting within the same request, therefore the javascript you wish to output will never be rendered.
1 solution would be to pass a querystring to your next page like:
Response.Redirect("AddToPicklist.aspx?alert=titleadded")
Then on AddToPicklist.aspx do:
If Request.QueryString("alert") = "titleadded" Then
Response.Write("<script>alert(" & "'Image Title added successfully'" & ")</script>")
End If
Alternatively you could redirect to the page via javascript after the alert, but this would be bad for users who do not have javascript enabled.
On a side note, look into the use of ClientScriptManager.RegisterStartupScript for outputting javascript, rather than Response.Write
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
The Redirect will be making the page (or another page - not sure what your pages are called) reload from scratch and so the click event will not be entered again and the <script> will not be inserted.
I would advise against producing messages on the client by using Response.Write. At the very least use registerclientscriptblock eg
RegisterClientScriptBlock("showSaveMessage", _
"<script language=""JavaScript""> _
alert('Your changes have been saved.'); _
</script>")
(from MSDN)
But I would instead consider using a WebService to write to your DB. And then you won't have to have a full postback.
I am going to use Response.Write("<script type='text/javascript'>{ alert('Image Title added successfully'); document.location.href = 'AddToPickList.aspx'; }</script>")
the question says it all : i have a linkbutton to which i pass through CommandArgument a value and i need that value to be a javascript value. Thanks!
Edit :
here is my linkbutton tag :
< asp:linkbutton id="prevBut"
runat="server" OnCommand="load_com"
CommandArgument=to_place_javascript_string
Text="previous" />
and the function :
public void load_com(object sender, CommandEventArgs e)
{ //get the string from e and search through the database for something }
i want to pass the name of a photo that is stored in a variable $.galleria.current.
You need to stop for a moment and think about what the LinkButton is actually doing. It's not magic. It's just posting the form for you.
As such, you can...
define an onsubmit handler to stuff that javascript value into a hidden form field
or, replace that LinkButton with a simple <a onclick="dostuff()"> pointing at a function that stuffs your value into a hidden form field and submits the form
or, replace that LinkButton with a simple <a onclick="dostuff()"> pointing at a function that constructs a URL containing ?myvalue=whatever and redirects to it.
There's no reason you need to involve ASP:LinkButton in any of it. If the built-in ASP.NET controls aren't doing what you want. All you need to do is stop using them.
(Incidentally, you'll have a much happier and more productive career in the .NET world if you stop using Microsoft's Rich Controls in favor of their HTML equivalents. Those things are there so that non-programmers can drag/drop their way to unmaintainable websites. Since you're here, we can assume you're not a non-programmer, and are therefore smart enough to ignore the marketing portions of ASP.NET and use the good stuff directly.)
Are you looking to place a string of javascript code in the command argument or a value which can be accessed via javascript?
If you need a value to be accessible via javascript you could put the command argument value in an attribute of the linkbutton <a href="javascript:void(null)" commandArg="value" >Link Text</a> this would make "commandArg" available via jQuery like $('#linkID').attr('commandArg') . You could obviously name that attrubute whatever you need to.