Assign C# string to Javascript variable - javascript

var nUserID = '<% if (ids != null) {ids.userID.ToString();}%>'
Note: ids is not null nor ids.userID is null but em getting nUserID = ""
Is there any way to convert C# string to Javascript string?

For write it direct on page you need to use the Response.Write as
var nUserID = <% if (ids != null) {Response.Write(ids.userID.ToString());}%>
beside that, if you need to add at the end ; or place it inside quotas is up to you.
The <% %> did not write on page, just run the code.
The <%= %> write on the page as the Response.Write

var nUserID = '<%=((ids != null) ? ids.userID.ToString() : "0")%>';

Use Something Like this:
<script type="text/javascript">
var nUserID = '<%=ids.userID.ToString()%>';
if(!nUserID)
{
//check for null in javascript
alert(nUserID);
}
</script>

More appropriate solution would be to to save your ids.userID to data attribute of some related html element or just create invisible div element with all C# data you want to use in your javascript code as data attributes. And then use jQuery to extract that data in scripts.
<div id="settings" style="display: none;" data-user-id="<%= ids.userID %>"></div>
and javascript:
var nUserID = $('#settings').data('user-id');

Related

How To Use Javascript Variable In html attribute string

I am New to This
I am writing this code
"OnClientClick="return OpenRadWindow('ImportSDS.aspx?id=##', 'RWImport');" >
i have js variable
var id = "<%=this.id %>";
So I want to Use This id Varable at ## How It Is Possible Please Help.
If you have the variable available, you should just use it in the method instead.
I don't have enough of your code really to go on but something like this.
function OpenRadWindow(url, x) {
var id = "<%= this.id %>";
url = url + id;
... then your code here
}
Then for your OnClientClick
OnClientClick="return OpenRadWindow('ImportSDS.aspx?id=', 'RWImport');"

Compare variable values in scriplet and javascript

I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax

Show/Hide Database Field based on Null/Not Null ASP.NET

I am trying to hide a data field if it is null via ASP.NET.
I have the following setup:
<script runat="server" type="text/vb">
// target the id called test
var test = document.getElementById("test");
// if test is not empty, show
// else hide test
if (test.value != null){
document.getElementById("test").style.visibility = visible;
}else{
document.getElementById("test").style.visibility = hidden;
}
<p><asp:Label runat="server" id="test"><%# Eval("DBField")%></asp:Label></p>
Am I way off here? I am getting error in whatever I try. I don't think it should be so complicated however...any thoughts/recommendations would be greatly appreciated.
Thank you in advanced,
Without knowing what your error is it's hard to give you an answer. One thing that jumps out is that you are not using the ClientId of the asp.net control. Try changing this:
var test = document.getElementById("test");
to this:
var test = document.getElementById("<%=test.ClientID%>");
When you assign an ID to an asp.net control, that is not the ID that gets rendered. Give this article a read for more info on that.
There are a few possible issues here:
Since you are using a server control, depending on what its parent is, the ASP.NET runtime could be changing its ID. If you View Source on your page it may show an ID like "ctl00_main_test" or something similar. To get aroud this you have to do the followinh:
var test = document.getElementById("<%= test.ClientID %>");
if (test.text != null){
test.style.visibility = 'visible';
}else{
test.style..visibility = 'hidden';
}
Since "visibility" maps to a CSS style, you probably have to use quotes around "visible" and "hidden"
Lastly, getElementByID should work well for all modern browsers, but older browsers could have flaky implementations. I suggest looking at jquery to simplify this code:
if ( $('#<%=test.ClientID>').text() != '' && $('#<%=test.ClientID%>').text() != null){
$('#<%=test.ClientID%>').show();
}else{
$('#<%=test.ClientID%>').hide();
}
You need to test against empty string in JavaScript, like this:
var test = document.getElementById("<%=test.ClientID%>");
if (test){
test.style.visibility = (test.value == "" ? "hidden" : "visible");
}
EDIT
I just noticed that you're using databinding syntax, which makes me think that this Label is inside of a grid or something. You can try something like this instead:
<asp:Label ID="test" runat="server" Visible='<%#(String.IsNullOrEmpty(Eval("DBField")) == false)%>'><%#Eval("DBField")</asp:Label>
I was able to hide data via the following code:
<asp:PlaceHolder ID="PlaceHolder" runat="server" Visible='<%# IIf((Eval("test")).ToString().Length > 0, "true", "false") %>'>
<h3>test</h3>
<asp:Label ID="test" runat="server" Text='<%# Bind("test") %>'></asp:Label>
</asp:PlaceHolder>
Span tags do not have a value:
if ($('#<%=test.ClientID%>').html() != "") //jQuery
or
if (document.getElementById("<%=test.ClientID%>").innerText != "")

How to use Javascript to get ASP.NEt Web Forms label's value?

I have the following label control:
<asp:Label ForeColor="DarkGreen" runat="server" ID="lblStatus"></asp:Label>
Its value is filled in the Page_Load event.
I attached the following Javascript (placed at the end of the page, not Master page):
function Validate() {
var lblObj = document.getElementById('<%=lblStatus.ClientID%>');
alert(lblObj.value);
if (lblObj.value == "Replaced" || lblObj.value == 'Trashed' || lblObj.value == "Internal Use") {
alert("Products with" + lblObj.value + "status cannot be reserved");
return false;
}
}
The alert(lblObj.value) displays a popup with text "undefined". How can I fix this problem? Please, I tried many combinations for placing the JavaScript but no luck! Thanks
UPDATE
Browser soruce code:
<span id="ctl00__main_lblStatus" style="color:DarkGreen;">Available</span></td>
First line of Validate JS function:
function Validate() {
var lblObj = document.getElementById('ctl00__main_lblStatus');
labels don't have a value. They have innerHTML and innerText.
Use JQuery and it will run in all browsers and platforms, something like:
$('#<%= lblStatus.ClientID %>').next().text();
source: JQuery: getting the value/text/innerHtml of a checkbox in an ASP.NET CheckBoxList control
Label server control renders as span. So you should get it's content by innerText. try this :
alert(lblObj.innerText);
ASP.NET label server control will be rendered in complex HTML output.
Like:
<span id="ctl00_ctl00_ContentPlaceHolder1_BodyPlaceHolder_lblLanguage0">
<label class="inputText">English</label>
</span>
When you use getElementById you will get span.
But to set value via javascript you have to access inner label object
try this
<script language="javascript" type="text/javascript">
function getlabelvalue()
{
var value1 = document.getElementById('<%=labelID.ClientID%>').value;
if (value1.length < 1)
value1 = 0;
}
</script>
With jquery you need to use the html method.
var g = $('#<%=lblStatus.ClientID%>').html();
These will NOT work with jquery:
$('#<%=lblStatus.ClientID%>').innerText
$('#<%=lblStatus.ClientID%>').innerHTML
$('#<%=lblStatus.ClientID%>').val()

ASP.NET MVC 3 Razor: How to get Action URL in a Javascript string variable?

#(Html.ActionLink("Link Label",
"ActionMethodName",
"ControllerName",
null, // parameter object, then html object
null))
produces
Link Label
If I want to reference the /ControllerName/ActionMethodName/id in a JavaScript template for the Edit or New link, how would I assign that to a JavaScript variable?
attempt:
<script type="text/javascript">
var actionUrl = '#(Html.ActionLink("","ActionMethodName",
"ControllerName",null,null))';
</script>
but at that point, I would have to use Javascript to remove the unwanted <a href... characters in the string.
#Url.Action("ActionMethodName", "ControllerName") will generate a path.
<script type="text/javascript">
var actionUrl = #Html.Raw(Json.Encode(Url.Action("ActionMethodName", "ControllerName")));
</script>
or if you already have this actionLink somewhere inside the page you could use it directly:
var actionUrl = $('#mylink').attr('href');
Just ensure to provide a unique id in order to simplify the selection:
#(Html.ActionLink(
"Link Label",
"ActionMethodName",
"ControllerName",
null,
new { id = "mylink" })
)

Categories