I am trying to write javascript variable(hdnField) to server side. In javascript code I have assigned the value of "HiddenField" Control and then I want to write this value to server side. Here's my Client side script:
<script type="text/javascript">
var hdnField = document.getElementById('<%= hdnField.ClientID%>');
hdnField.value = 100;
</script>
Server side:
<form action="#" runat="server">
<div class="left"><%Response.Write(hdnField.Value);%></div>
<asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>
</form>
I viewed the Page src and was able to retrieve the "hdnField" which is :
<input id="hdnField" type="hidden" name="hdnField" value="100 ">
I don't know where
<div class="left"><%Response.Write(hdnField.Value);%></div>
Comes into play because that looks more ASP than ASP.NET web forms, but if you have:
<asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>
You can read and write to this on the client via:
document.getElementById('<%= hdnField.ClientID %>').value = 'XYZ';
alert(document.getElementById('<%= hdnField.ClientID %>').value);
On the server, you can read and write to this via:
hdnField.Text = "XYZ";
var text = hdnField.Text;
As long as hdnField is not in a template or list control, you can refer to it directly on the server, with the <asp:HiddenField> control you can do both. This bridges the gap so that you can change the value on the client, then retrieve the value on postback. AJAX is only necessary if you need to send the value to the server before the next postback occurs, or out of the normal flow of the ASP.NET postback lifecycle.
Related
I want to pass data from back-end to front-end and front-end to back-end so far I have tried like below
back-end to front-end :-
back-end (.aspx.cs):-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
}
front-end (.aspx):-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert(amt); // data coming
</script>
</form>
</body>
The above example is working fine but while passing the value from front-end to back-end I'm getting the null("") value (for this concept I have read this article)
front-end to back-end :-
front-end (.aspx) :-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert("amt :- " + amt);
function getval() {
var keyid = "1234";
document.getElementById('key_id').value = keyid;
alert(document.getElementById('key_id').value);
alert('hit');
window.location.href = "http://localhost:49855/ValuePassig.aspx";
}
//alert(amt);
</script>
<input id="key_id" runat="server" type="hidden" name="key_id_1" />
<input type="button" id="btn" value="click" runat="server" onclick="getval()" />
</form>
</body>
back-end(.aspx.cs) :-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
//I'm getting the null("") value
//string kId = this.Request["key_id_1"];
//string kId = Request.Form["key_id_1"];
string kId = key_id.Value; //Initially the value come null(acceptable) and next I'm clicking on the "click" button at that time null value should not come(but coming)
Response.Write(kId);
}
I did my best so far to achieve this concept and I don't why I'm getting a null value because, I have followed the article also(above mentioned link) to achieve this
concept
Suggest me where I did the mistake to pass the value from front-end to back-end and how to achieve this
Please give me your best suggestions.
Note :- I have changed the code for better understanding that is button added and when I click on the button the hidden value should come back-end.
Ok, so we want to have some value - set in code behind cs, to set/pass/have some value for use in the client side js code.
And of course in the js code, we want use of that value, and ALSO to be able to change that value, and then upon actions, or code behind, we want that value passed back to the code behind.
First up, don't use a server side expression to "set" that value for use in the js code. The reason of course then you don't have a easy way to pass back and have use of that change value in the code behind.
You can freely change the var in js code, but you really don't have a easy/nice way to get that value back to the code behind (so that <%= %> expression is a one way street to the client side.
There are a LOT of ways to do this, but probably best is to drop in a hidden field control (as per your question title)..
You can also use a hidden text box, but might as well use the hidden field.
So, lets on page load (and ONLY first page load - like all setup on the page should be inside of the !IsPostBack code block - all web pages quite much need this !IsPostBack code block).
And bonus?
the Hidden field control has automatic view state. (that means the value will persist on page post-backs).
So, lets drop in a server side button to "show" the value.
And THEN lets drop in a button (client side) to show the value, and ALSO to modify the value.
<asp:HiddenField ID="MyHotelName" runat="server" ClientIDMode="Static" />
<h3>Server side code</h3>
<asp:Button ID="cmdShowServer" runat="server" OnClick="cmdShowServer_Click"
Text="Show Hotel Name" CssClass="btn" />
<br />
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<h3>Client side code</h3>
<asp:Button ID="cmdShowClient" runat="server" Text="Show Hotel Name"
OnClientClick="ShowHotel();return false" />
<br />
<asp:Button ID="cmdChangeClient" runat="server" Text="Change Hotel Name"
OnClientClick="ChangeHotel();return false" />
<script>
function ShowHotel() {
alert("Hotel name = " + $("#MyHotelName").val())
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
$("#MyHotelName").val(sHotelNew)
}
</script>
And our code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyHotelName.Value = "Zoo";
}
}
protected void cmdShowServer_Click(object sender, EventArgs e)
{
lblShow.Text = "Value of hotel = " + MyHotelName.Value;
}
So, we now have this:
Edit: Above used jquery.
Of course the js code above used jQuery.
however, we could assume pure js code, no jQuery.
so, the js code would then become this:
<script>
function ShowHotel() {
sHotel = document.getElementById("MyHotelName").value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById("MyHotelName").value = sHotelNew
}
</script>
I should also point out the "very" imprortant adding of clientidmode="static" for the hidden field. This will "prevent" asp.net system from changing the "id" used for the control, and as a result, the js code tends to be more "clean" and "easy" to reference controls.
If you don't want to use clientidmode=static for the hidden field, then the above code then becomes this:
hidden field thus is this: (no client id mode).
<asp:HiddenField ID="MyHotelName" runat="server" />
And now our code becomes this:
<script>
function ShowHotel() {
sHotel = document.getElementById('<%= MyHotelName.ClientID %>').value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById('<%= MyHotelName.ClientID %>').value = sHotelNew
}
</script>
So, I often will toss in a ClientIDMode="static" for the hidden field, as that makes the js code to get the hidden control less messy.
Im trying to redirect a user to a new page in which there username will be displayed within a text box. I am using ASP.NET Loginname and Buttons to do this. My issue is that im not 100% sure on how to get the value from the LoginName into the javascript which needs this. I have no way to get into the server code so this all has to be done by SharePoint designer
I know the common way is to do something like this
window.location="http://mysite/default.aspx?u="+ LoginName1
But this seems it doesn't want to work. Any answers?
JavaScript Code
function Redirect()
{
window.location="http://mysite/default.aspx";
}
ASP.NET Code
<asp:Button runat="server" Text="To Sysomos" id="Button1" OnClientClick="if (!Redirect()) { return false;};"></asp:Button>
<asp:LoginName runat="server" id="LoginName1" ></asp:LoginName>
try something like this
<script>
var usrName = "#HttpContext.Current.User.Identity.Name";
</script>
window.location="http://mysite/default.aspx?u='+ usrName + '";
Reference :
How to get the current login user name in my Script file inside my asp.net mvc
Assuming you are using SP2010, you can use Sharepoint's Client Object Model to get the current user details.
<script type="text/javascript">
(function () {
var spUser;
// Ensure SP objects have been loaded before executing our code
ExecuteOrDelayUntilScriptLoaded(getSpUser,"sp.js");
function getSpUser() {
var clientContext = new SP.ClientContext.get_current();
var spWeb = clientContext.get_web();
spUser = spWeb.get_currentUser();
clientContext.load(spUser);
clientContext.executeQueryAsync(getSpUserSuccess, getSpUserException);
}
function getSpUserSuccess(sender, args) {
var curUserId = spUser.get_loginName();
// redirectToSomeAspxPage();
}
function getSpUserException(sender, args) {
// Do any necessary error handling.
}
})();
</script>
Only issue with this is that the time to redirect may take (slightly) longer as the code needs to wait for sp.js to load before you can get the current user's details. Alternatively, you can redirect without the username on the query string, and simply retrieve the username from your ASPX page using the above code.
You can find the username and other things for the current user. To do it, start by adding this line at the top of your .aspx page: <%# Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
(Version=14.0.0.0 for Sharepoint 2010 and Version=12.0.0.0 for Sharepoint 2007)
Now, just after the <form> tag add this line:
<form>
<SPSWC:ProfilePropertyLoader runat="server"/>
Finally add the below block before the </form> tag:
<div id="userDetails" style="display:none">
<asp:LoginName runat="server" id="userLogin">
<SPSWC:ProfilePropertyValue PropertyName="FirstName" ApplyFormatting="false" id="userFirstName" runat="server"/>
<SPSWC:ProfilePropertyValue PropertyName="LastName" ApplyFormatting="false" id="userLastName" runat="server"/>
<SPSWC:ProfilePropertyValue PropertyName="WorkEmail" ApplyFormatting="false" id="userWorkEmail" runat="server"/>
<SPSWC:ProfilePropertyValue PropertyName="PreferredName" ApplyFormatting="false" id="userPreferredName" runat="server"/>
</div>
So in your page you'll see a "userDetails" block with the current user login, firstname, lastname, work email and preferred name. With JavaScript you can get the username with :
document.getElementById('ctl00_userLogin').innerHTML
I have a hidden field in my form, I'm setting the hidden field's value on the server and trying to access this value from javascript,
I get the error: Unable to get value of the property 'value': object is null or undefined
If I view the source the hidden field value is set and the ID of the hidden field is the same as the ID I'm calling.
ASPX
var v = document.getElementById('hxValue').value;
<asp:HiddenField ID="hxValue" runat="server"/>
VB
hxValue.Value = "Value1"
I recall doing this before and it should be relatively simple but for some reason, i'm not getting it right.
Your code will work. For simple forms, just add
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
OR
you need to find the client id using
'<%=hxValue.ClientID%>'
Ok it appears my hidden field's value had not been set before the script had run, therefore receiving a null value. I had assumed that placing breakpoints on the server page load and the script would establish if the control was being set before the script ran, appears not.
Fixed as below:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript">
function GetHiddenValues() {
var v = document.getElementById('<%= hxValue.ClientID %>').value;
}
</script>
</head>
<body onload="GetHiddenValues() ;">
<form runat="server">
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
</form>
</body>
</html>
Thanks for all the assistance.
You can use innerText not value to retrieve the value of hxValue.
var v = document.getElementById('hxValue').innerText
If you were using jQuery you could also do
var v = $("#hxValue").val();
Try this
var v = document.getElementById('<%= hxValue.ClientID %>').value;
Problem is that Hidden Field is server side control and it's ID that you have given is a server side ID, you will have to get client side ID of that control to refer it in your client side JavaScript or Jquery.
Update
put this script at the end of your page, just before </body> something like this
<script type="text/javascript" language="javascript">
var v = document.getElementById('<%= hxValue.ClientID %>').value;
</script>
</body>
Try <asp:HiddenField ID="hxValue" runat="server" Value=""/>
Then call it by id and set value
Is there any way to pass the value of a parameter from a Servlet to JavaScript ?
the following didn't work.
var val = req.getParameter('valid');
This won't work because the ServletRequest only exists at the server and your JavaScript is running at the browser. It is easy to get the difference confused, because the code that runs on the server and the code that runs in the browser are very often both written in the same file (someServlet.java or somePage.jsp), so you have to remember how everything will sit at runtime.
What you can do, as a way of passing information that is retrieved from the request in the servlet to the JavaScript, is embed the data in the structure of the page on the server side. The page and its structure are then passed to the browser and the JavaScript has access to the full page structure on the client side. So you put something like this in the servlet:
<form name="data" action="" >
<input type="hidden" id="parmEmpId"
value='<%= request.getParameter( "EMPLOYEE_NUMBER" ) %>' />
<input type="hidden" id="parmServerName"
value="<%= request.getServerName() %>" />
</form>
And then, in your JavaScript, you can pull the data from the page:
var employeeId = $("#parmEmpId").val(); //Using jQuery
var server = $("#parmServerName").val(); //Using jQuery
I have two list controls in my asp.net page and am populating the second list control using javascript. Problem is the script executes and i can see the value moved from first list box (ConfiguredOrgListBox) to second list box(SelectedOrgListBox) but when i try to save using submit button i find my second list as empty and first list box as it was earlier. Below is the script and mark up.
//call this method to register the script
private void CreateMoveOrganizationScript(StringBuilder sb) {
sb.Append( #"<script language=javascript type=text/javascript>;
function moveOrganisation() {");
sb.Append( #"var source = document.getElementById('"+ ConfiguredOrgListBox.ClientID +#"');
var target = document.getElementById('"+SelectedOrgListBox.ClientID+ #"');
if ((source != null) && (target != null)) {
var newOption = new Option();
newOption.text = source.options[source.options.selectedIndex].text;
newOption.value = source.options[source.options.selectedIndex].value;
target.options[target.length] = newOption;
source.remove(source.options.selectedIndex) ;
}
} </script>");
}
Markup
<asp:Label ID="ConfiguredOrgLabel" runat="server" Text="Available Organizations"></asp:Label><br />
<asp:ListBox ID="ConfiguredOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
<input id="MoveOrgRight" type="button" value=">>" onclick="moveOrganisation()" />
<asp:Label ID="SelectedOrgLabel" runat="server" Text="Selected VNA Organizations"></asp:Label><br />
<asp:ListBox ID="SelectedOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
Please let me know what I am doing wrong
Regards,
JeeZ
According to this, it's because the list box doesn't post back to tell the back-end that it's changed. They use a hidden field which holds info on what changes were made with JavaScript and then on postback it updates the back-end.
You need to process these changes during postback. When postback happens ASP.NET engine loads control's data from view state and it doesn't know that client modified values using javascript, so you should manually extract those values from Request.