Server-side code working with JavaScript using ASP.NET - asp.net

I am trying to get a server side code working with JavaScript. What am I doing wrong?
function openUp(name)
{
document.getElementById(name).style.display = <%if (Request.ServerVariables["HTTP_USER_AGENT"].Contains("FireFox"))Then %>
response.write('table-row'); <%else%> response.write('block');
}

Your Response.Write statement (which is not properly cased) should be inside the <% %> tags. You also seem to have an odd mixture of C# and VB.NET in your code. Which of the following are you using?
C#
document.getElementById(name).style.display =
<% if (Request.ServerVariables["HTTP_USER_AGENT"].Contains("FireFox"))
Response.Write("'table-row'");
else
Response.Write("'block'"); %>; // Semi-colon outside of %> is for JavaScript
VB.NET
document.getElementById(name).style.display =
<% If (Request.ServerVariables("HTTP_USER_AGENT").Contains("FireFox")) Then
Response.Write("'table-row'")
Else
Response.Write("'block'")
End If %>; // Semi-colon outside of %> is for JavaScript

To answer your question, you can update your code to;
C#
document.getElementById(name).style.display = '<%Response.Write((Request.ServerVariables["HTTP_USER_AGENT"].Contains("FireFox") ? "table-row": "block")); %>';
VB
document.getElementById(name).style.display = '<%Response.Write(IIF(Request.ServerVariables["HTTP_USER_AGENT"].Contains("FireFox"), "table-row", "block")) %>';

Related

Hide controls in ascx without access to code behind

I have a website which is written in VB.NET. I do not have access to code behind and only have access aspx/ascx pages. I have some controls like this in my ascx file.
<img src="../css/icons/login.svg" />
I want to make them visible based on if user is logged in or not logged in. I remember it is possible to put the code in design files but I do not remember the syntax in VB.NET and make it visible/unvisible for these controls.
If you do not need to access that link in code behind, which would seem to be the case, you can construct the html as a ternary operator. That way you avoid binding expressions.
<%= Request.IsAuthenticated ? "Login" : "" %>
Or as an inline if statement
<% if (Request.IsAuthenticated == false) { %>
Login
<% } %>
VB Example
<% Dim IsAuth As String = IIf(Request.IsAuthenticated = False, "Login", "") %>
<%= IsAuth %>

Dynamic values for asp control

I'd like have the following type of code fragment in a .aspx page:
<% foreach( int i in <some-expression> ) { %>
<asp:linkbutton CommandArgument="<value-of-i>" OnClick="<some-handler>" runat="server" />
<$ } %>
Basically, I want to generate the page sans data binding, but supply the value of CommandArgument to the linkbutton from a variable in the code behind, so that when the click handler activates, I can retrieve the value of the variable from the CommandArgument, that existed when the code ran.
I do not want to use data binding, for various reasons. Is this possible? I understand that the <%: ... %> syntax is equivalent to Response.Write, and that the syntax <%# %> retrieves values which are databound. I also know that I can't use the <%: %> syntax here to solve my problem. And because I am not using data binding, I can't use the <%# %> syntax.
It seems to me that something like this should be very basic.
So, to answer my own question, there seems to be no way to mix server side controls and state generated from the code around them. The reason being that server side controls are generated before the code runs, and the code, for the most part, runs to emit the response (think Response.Write).
However, one can "manually" cause the post back that server side controls, like asp:LinkButton, perform with a java script call to __doPostBack. So the solution to my problem is something like the following:
<% for( int i = 0; i < 10; i++ ) { %>
<a href="" onclick='javascript:__doPostBack( "MeClicked", "<%: i %>" ); return false; '>Click Me <%: i %></a>
<% } %>
Where Page_Load does something like::
if ("MeClicked".Equals( Request.Form[ "__EVENTTARGET" ] )) {
string arg = Request.Form[ "__EVENTARGUMENT" ];
Response.ClearContent();
Response.Write( arg + " Clicked" );
Response.End();
return;
}

Print code behind function return value in aspx page

I'm sure this is trivial, but why isn't the Windows Authentication user printing in my ASP.NET page inline?
Code behind function:
public string GetCurrentUserWindowsLogin()
{
string windowsLogin = Page.User.Identity.Name;
int hasDomain = windowsLogin.IndexOf(#"\");
if (hasDomain > 0)
{
windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
}
return windowsLogin;
}
Inline code:
<div class="loginDisplay">[ <%#GetCurrentUserWindowsLogin() %> ]</div>
The <%#... %> is used for Binding Expressions like Eval and Bind.
So if you call Page.DataBind() in page_load it should work.
Another way that should work is to use code render blocks which run normal code:
<% GetCurrentUserWindowsLogin() %>
or the <%= %> construct used for small chunks of information:
<%= GetCurrentUserWindowsLogin() %>
Just a follow up on the above answer, the <%= is like response.write.
http://msdn.microsoft.com/en-us/library/vstudio/6dwsdcf5(v=vs.100).aspx

ASP.NET Aspx View - How to Remove Unused Variable Warnings

My company has a zero warning tolerance policy and I have a warning that I just can't get to go away. It is showing on the declaration of the string because
Warning 1 The variable 'message' is assigned but its value is never used
This is the code snippet:
<%
string message = "Message to be displayed";
if (Model.Count == 0)
{
%>
No records to display. <%= message %>
<%
}
else
{
%>
The rest of the code is correct, so it's not a syntax error.
Why would this kind of warning appear in the first place when I am clearly referencing it?
Thx in advance!
It's strange that your company has 0 tolerance to errors and still lets you write C# code in your views which turn them into spaghetti. Also you are hardcoding urls instead of using URL helpers which is very bad.
So you could start by slightly improving the code:
<% if (Model.Count == 0) { %>
No records to display.
<%= Html.ActionLink("Click here to add.", "Details", "ObjectDefinition") %>
<% else { %>
...
<% } %>
Change the declare as below, this issue will be fixed.
When you see this kind of warning, just review the declare. It will OK then.
<%
if (Model.Count == 0)
{
string message = "Message to be displayed"; // declare message here :)
%>
No records to display. <%= message %>
<%
}
else
{
%>
Best regards.

Get value of a query string from asp.net mvc controller action to <script type="text/javascript">

I am passing a query string with name "RowTobeHighLighted" from my Asp.net mvc action result. What I have to do is, I have to get the query string value from that controller action to a script of type text/javascript. I have tried to use simple Request.Querystring() under javascript. But that is not working.
Is it possible to get the querystring value from controller action.Or, is it possible to get the value of viewdata under <script type="text/javascript"> tag.
Well no, Request.QueryString won't work, because it's server side only.
You have a few options
You could use Request.QueryString to embed the value in a script
var myValue = <% = HttpUtilityRequest.HtmlEncode(QueryString["myValue"]") %>
You could either pass the query string value as view data to the view and then use it in your javascript like so
var myValue = <% HttpUtilityRequest.HtmlEncode(ViewData["myValue"]) %>
Or you could look at the query string in javascript
var qs = new Querystring()
var myValue = qs.get("myValue")
Of course with all of these you should watch for Cross Site Scripting attacks.
On the client side: use the Querystring.
On the server side: (provide value to JS):
<%= "var RowTobeHighLightedUrl = '" + Request.QueryString["RowTobeHighLighted"] + "';"%>
If the RowTobeHighLighted should be JavaScript Escape (NOT HtmlENcode!).
Use TempData for this sort of temporary message.
In your controller:
TempData["RowToHighlight"] = rowNumber;
And then in the view:
<% foreach (var row in Model) { %>
<tr>
<td id="row_<%= row.id %>"<%= (row.id == (int)TempData["RowToHighlight"]) ? " class="highlighted" : "" %>>my row</td>
</tr>
<% } %>
And then if you were using jQuery for example to fade out or whatever (inside your of jQuery document.ready):
<% if (TempData["RoToHighlight"] != null) { %>
$("#row_<%= (int)TempData["RowToHighlight"] %>").fadeOut();
<% } %>
Of course, be sure to use any necessary escaping and encoding etc.

Resources