i am hoping someone will help me, i am pulling out my hair for the last few hours...!
I am using asp.net web forms with c#
I have the following button in my menu , this button opens up a page that lists selected properties for realtor…
htmlCode.Append("<button type='button' class='btn btn-basic' id='btnEnquire' onclick='openEnquiryPage()'> <span class='glyphicon glyphicon-th-list'></span> View my list </button>");
function openEnquiryPage() {
location.href = "EnquiryPage.aspx";
//get the list from the storage into the hidden field
//getListOfProperties();//not in use...
}
The list is stored in localstorage as Json, I can see the correct data in the text box on the page
var retrievedData = localStorage.getItem("propertyArray");
proplist2.value = retrievedData;
declared as follows in asp.net control
<asp:TextBox ID="TextBox1" runat="server" Text="initial"></asp:TextBox>
BUT in the hidden field, the data is always = ""
<asp:HiddenField ID="txtPropList" runat="server"></asp:HiddenField>
javascript to populate the hidden field...
function getListOfProperties() {
document.getElementById("body_content_txtPropList").value = retrievedData;
var proplist2 = document.getElementById("body_content_txtPropertyList");
proplist2.value = retrievedData;
}
when I debug the following lines in the code behind ...
Page.ClientScript.RegisterStartupScript(this.GetType(),"prop", "getListOfProperties();",true);
_propertyListJson = txtPropList.Value;
propertyListJson I always = “”
Thank-you in advance.!
If you want to use the hidden field then you should use
<%=txtPropList.ClientID%>
as on when you render the page and see it in inspect element server would render the different Id so it would not store the value in hidden field simply so it is feasible to use ClientID to create the static mode. But as on when you call the javascript function from the c# code then it would call the javascript function but it would not wait for it and execute the next line of code as on at that time the value is not store in hidden field so it would return the null value.
If you want then call the function of javascript on page load event and then click the button and retrieve the value it would successfully retrieve the value but i dont think that these would be the feasible code from my opinion
I suggest to create the WebAPI which would simply get the the data from the localstorage and perform the operation
And webAPI can be easily called from javascript using ajax call
I hope this would be helpful and answer is satisfactory 😊☺
Thank You ☺🙂
Related
I have web form and JavaScript function like this:
web form
<div>
<asp:DropDownList runat="server" ID="ddlType">
<asp:ListItem Value="1" Text="Type1"></asp:ListItem>
<asp:ListItem Value="2" Text="Type2"></asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="lnkTest" OnClientClick='<%= "getValue('0' + '|' + 'ddlType.SelectedValue');return false;" %>' runat="server" Text="text">
new
</asp:LinkButton>
</div>
JavaScript function
<script>
function getValue(Input) {
var result = Input.split("|");
section1 = result[0];
section2 = result[1];
}
</script>
I need to pass string includes '0' (hardcoded) and ddlType.SelectedValue to getValue.
This web form has syntax error Server tags cannot contain <% ... %> constructs (I know). I can get selected value by getElementById but I want to pass SelectedValue as argument. I read many posts but none of them don't pass SelectedValue.
It would be very helpful if someone could explain solution for this problem.
SelectedValue is a server-side value. It's available to the server-side code at page load (i.e. before the page is rendered to the user). In javascript it has no meaning at all, and isn't available at the time when a user clicks on the link.
If you want to get the selected value on the client side you can do something like this:
First get rid of the all the OnClientClick code from your LinkButton.
Second, write some javascript like this (at the bottom of the page, after all your HTML/ASP markup:
document.getElementById("<%=lnkTest.ClientID %>").addEventListener("click", function(event) {
event.preventDefault(); //stop default action of the link button, to allow script to execute
var selectedVal = document.getElementById("<%=ddlType.ClientID %>").value;
getValue('0|' + selectedVal);
});
This will cause the browser to listen for a user clicking on the button, and then run the JS function given. That function fetches the currently selected value of the dropdown (as selected in the browser - at this point the server has no idea what's selected because no postback has happened) and passes that selected value to your existing getValue function.
N.B. In case you're wondering, the reason I use the contruct <%=ddlType.ClientID %> is because ASP.NET dynamically creates the client-side ID of each element based on the structure of the server-side controls it lies within. So just relying directly on the server-side ID (e.g. "ddlType") will not reliably identify the element in the rendered DOM. .NET provides the ClientID value at runtime in order to allow us to access the generated ID.
I need some assistance with the telerik radgrid's itemcommand to get some information from a user adding a new record prior to opening the Grid in Insert mode. I have the itemcommand working to open a radwindow, present the user with a dropdown list of items to select from and a radbutton to select the value and close the radwindow, then this value is passed back to the parent page in javascript. All the values are passed down and I can use the alert function to validate this.
So at this point I need to continue the flow to open the radgrid in insert mode and filter a dropdown in the insertmode using the value from the radwindow noted above. In order to use this value I'm attempting to assign it to a hidden radtextbox for use in the ItemDatabound event when the form is loading in insert mode. Unfortunately, the value isn't being set via the javascript in this hidden control and is acting like it is erroring somewhere in the javascript. I feel like I'm overcomplicating this but was hoping for some guidance on what others have done to implement something like this.
<asp:LinkButton ID="addNewRecord" runat="server" Text="Add New Record" OnClientClick="openWin(); return false;" OnClick="InitInsert">Add New Record</asp:LinkButton>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
//<![CDATA[
function openWin(sender, args) {
var oWnd = radopen("ParserFileNewDialog.aspx", "RadWindow1");
}
function OnClientClose(oWnd, args) {
//get the transferred arguments
var arg = args.get_argument();
if (arg) {
var lenderid = arg.LenderID;
var tb = null;
tb = $find("<%=newLenderID2.ClientID %>");
alert(tb.get_text());
tb.set_text(lenderid);
$find("<%=hdnInsertBtn2.ClientID %>").click();
}
}
//]]>
</script>
</telerik:RadCodeBlock>
Any help is greatly appreciated!
What type of control is the newLenderID2 that you attempt to set a value to? With this syntax, it should be a RadTextBox. If it is an asp:HiddenFiel, you need
$get("<%=newLenderID2.ClientID %>").value = lenderid;
If you get an error - what is the error?
Also, you can fire a grid command and pass an argument to it (depending on the command) directly via the grid's masterTableView client-side API and the fireCommand() method: http://www.telerik.com/help/aspnet-ajax/grid-gridtableview-firecommand.html. Thus, you may not need the hidden button at all. A hidden field will suffice for data transmission.
I guys, I'm creating a VB.NET application, and this is the first time that I used Session Variables.
What I want to do is to pass the session variable from a page (first.aspx) to another page (second.aspx) via url.
Here an example of what I want to do:
In the first.aspx.vb page I declare a session variable and assign to it a value
Session("example") = "example123"
Then I pass this Session Variable to the first.aspx page
Response.Write(Session("example"))
and via javascript read the value of the Variable
<script type= text/javascript>
var SessionVar = '<%=Session("example")%>)';
</script>
Now, what I want to do is to change the value of the Variable (for example setting it as example456), and then pass the variable to the second.aspx [for example with window.open()] so that the url not contains the value of the variable but its name:
url/second.aspx?value=example AND NOT url/second.aspx?value=example456
Infact I don't want that the user read the value of the variable.
Finally I have to read the value of the session variable in the second.aspx.vb via Request.QueryString("value") and do the various operations.
Is it possible ?
If not, there is anothe way to do this
Thanks for the help :)
To set session variable from javascript can be done like below:
Create a hidden field control on the first page
<asp:HiddenField ID="HiddenField1" runat="server" />
Client script to set value of the hidden field
function setVal(value) {
// if using jQuery
$("#<%= HiddenField1.ClientID%>").val(value);
// if using javascript
var hf = document.getElementById("<%= HiddenField1.ClientID%>");
hf.value = value;
}
Create a button or link to navigate to the second page
<asp:Button ID="Button1" runat="server" Text="Go to second page" OnClick="NavigateToSecondPage" />
or
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="NavigateToSecondPage">Go to second page</asp:LinkButton>
In the first page code behind, create the NavigateToSecondPage sub to handle the onclick event of the button/link
Protected Sub NavigateToSecondPage(sender As Object, e As EventArgs)
Session("example") = HiddenField1.Value
Response.Redirect("SecondPage.aspx")
End Sub
Therefore, in your second page, you can access the Session("example") value and it will have a new value set by the client script in the first page.
Session variables are called this way because they are passed automatically from one page to the other within the same session, so you should just modify the value of the variable whenever you want and then access it again in the second page to find the value. You don't need to pass anything explicitely.
I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <asp:Label> controls are updated via JavaScript to reflect these calculations:
document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;
This correctly updates the UI. However, when I try to access the value in the codebehind, the Text property is empty. This makes sense I guess, since I was updating the innerHTML property via the JavaScript.
//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text)
? 0.00
: Convert.ToDouble(TotalLoans.Text);
How do I update the Text property of the <asp:Label> via JavaScript in such a way that I can read the property in the codebehind?
Update
This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <asp:Label> to a disabled <asp:TextBox>. I'm setting the value of the new textbox as such:
document.getElementById('<%=TotalLoans.ClientID %>').value = TotalLoans;
Again, in the codebehind, the value of TotalLoans.Text is always equal to "".
I don't mind changing how I approach this, but here's the crux of the matter.
I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked.
Any advice how I can go about this?
Update 2
Regarding the answer by #James Johnson, I am not able to retrieve the value using .innerText property as suggested. I have EnableViewState set to true on the <asp:Label>. Is there something else I am missing?
I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.
Place HiddenField Control in your Form.
<asp:HiddenField ID="hidden" runat="server" />
Create a Property in the Form
protected String LabelProperty
{
get
{
return hidden.Value;
}
set
{
hidden.Value = value;
}
}
Update the Hidden Field value from JavaScript
<script>
function UpdateControl() {
document.getElementById('<%=hidden.ClientID %>').value = '12';
}
</script>
Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .
This one Works for me with asp label control.
function changeEmaillbl() {
if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
}
}
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
Instead of using a Label use a text input:
<script type="text/javascript">
onChange = function(ctrl) {
var txt = document.getElementById("<%= txtResult.ClientID %>");
if (txt){
txt.value = ctrl.value;
}
}
</script>
<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />
<!-- pseudo label that will survive postback -->
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />
<asp:Button ID="btnTest" runat="server" Text="Test" />
Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.
So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)
Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.
If you do not know how to do this, here is how I've gone about it in the past.
Create a hidden field:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.
<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />
Javascript Client Side Function:
function TestSubmit() {
try {
var message = "Message to Pass";
document.getElementById('__EVENTTARGET').value = message;
} catch (err) {
alert(err.message);
}
}
C# Server Side Function
protected void _Submit_Click(object sender, EventArgs e)
{
// Hidden Value after postback
string hiddenVal= Request.Form["__EVENTTARGET"];
}
Hope this helps!
The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.
I am working on website using ajax and C#. I started learning these languages a couple months ago, so I'm not always sure what the best practice is to accomplish things.
I have a form in which certain controls need to be hidden or shown depending on the user's action. It starts out showing an "id" field (along with other fields), but if the user doesn't know their id, they click a link which causes the "id" field to become hidden and displays a table that contains additional controls and a "find" button. I am currently using Javascript to handle the click and hide/display the controls:
function showSearchTable() {
document.getElementById('IDNumberRow').style.display = 'none';
document.getElementById('DontKnowId').style.display = 'none';
document.getElementById('infoSearchTable').style.display = 'block';
}
When the "find" button is clicked, the application attempts to look up the additional info in the database and tells the user the result. As a result of the server call, the page is re-loaded, which causes the table to become hidden again. Here's my problem: if the phone number cannot be found, I would like to keep the table visible so that the user can correct any mistakes.
I have tried adding code that makes the table hidden to the code-behind so that the post-back won't cause the table to become invisible:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
infoSearchTable.Visible = false;
}
}
However, as the table now contains the attribute runat="server" in order to see it in the c# code, I can't seem to reference it in my javascript code in order to set it visible from the client. I tried this for the javascript:
function showSearchTable() {
document.getElementById('IDNumberRow').style.display = 'none';
document.getElementById('DontKnowId').style.display = 'none';
var infoSearch = document.getElementById('<%=infoSearchTable.ClientID%>');
infoSearch.style.display = 'block';
}
and the table's html:
<table id="infoSearchTable" runat="server">
....table rows/columns containing controls
</table>
but I get an error saying that 'infoSearch' is null.
I think I'd be able to accomplish both tasks (set hidden table visible with Javascript, but keep it visible on post back) myself, but I think that my code would end up being more complicated than necessary, especially as I'm new to ajax, .net and C#. So I'm looking for advice - Am I on the right track? Did I use something the wrong way? Is there another way to do this?
if(!Page.IsPostBack)
{
infoSearchTable.Visible = false;
}
I think this will stop the control being sent back to the client (hence the null reference) - try something like:
if(!Page.IsPostBack)
{
infoSearchTable.Attributes.Add("style", "display: none;");
}
You can do something like that
<table id="infoSearchTable" runat="server">
....table rows/columns containing controls
</table>
and in the code behind
infoSearchTable.Attributes.Add("class", "yourclass");
in youe .css
.yourclass{display:none;}
Once you add runat="server" to an element, you have to reference it by the ClientID in JavaScript:
var table = document.getElementById("<%=infoSearchTable.ClientID%>");
if (table){
table.style.display = "none";
}
In ASP.NET when you use runat=server it takes your ID and modifies it to include other information from your program, I forget exactly what but I think the master page or namespace or something to make it unique. Your getElementByID() need to be changed to include all that other information (view source on a page to get the actual ID) or use a javascript framework like JQuery that has advanced selectors for finding elements on a page.