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

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.

Related

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;
}

DNN ASP Only show on homepage

Wondering if I can do something like this in my DNN skin to only show some html on the homepage and vice versa on the inner-pages with an else statement.
<% if ((url = "/" | url = "")) { %> Doesn't work… <% } %>
Also would be nice to know where the documentation is for this kinda stuff.
There are syntax errors. If you are using classic-asp then
<% if (url = "/" or url = "") then
your code
end if
%>

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

Dynamically add items to a collection in MVC2 using EditorFor()

I'm trying to do this: Editing a variable length list, ASP.NET MVC 2-style
In the post he mentions that it could be done with less code using Html.EditorFor(), but that it would be more difficult because of the indexes. Well, that's exactly what I want to do, and I don't know where to begin.
I'm an ASP.NET novice who just completed the Nerd Dinner tutorial before jumping into a project at work, so any help would be appreciated.
Update 1: Instead of generating a GUID for each item in the collection, I'd like to generate incremental indexes starting with 0. Right now the field names look like "gifts[GUID].value"; I would like them to be "gifts[0].value","gifts1.value" etc. but I don't understand how the collection keeps track and generates these indices.
In response to your update about generating indexes instead of GUIDs, the original linked article had a few comments from others that tried to solve the same issue but none of them worked for me. What I found was the collection with index was referenced in the following location:
html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix
So I wrote a helper function to parse out the index (and if there is a problem then the GUID would be generated)
public static string GetCollectionItemIndex(this HtmlHelper html, string collectionName)
{
int idx;
string sIdx;
if (Int32.TryParse(Regex.Match(html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix, #"\d+").Value, out idx))
{
sIdx = idx.ToString();
}
else
{
sIdx = Guid.NewGuid().ToString();
}
return sIdx;
}
I edited the BeginCollectionItem(..) function to call this helper function when setting the item index:
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : GetCollectionItemIndex(html, collectionName);
Hope this helps someone else!
Well, you begin by defining an editor template (~/Views/Shared/EditorTemplates/Gift.ascx):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Gift>" %>
<div class="editorRow">
<% using(Html.BeginCollectionItem("gifts")) { %>
Item: <%= Html.TextBoxFor(x => x.Name) %>
Value: $<%= Html.TextBoxFor(x => x.Price, new { size = 4 }) %>
<% } %>
</div>
And then replace the RenderPartial call with EditorForModel:
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<%= Html.EditorForModel() %>
</div>
<input type="submit" value="Finished" />
<% } %>
Once you've tried this you may come back and ask if you have any problems by explaining the symptoms.

ASP Question - How to count # of characters?

Today is the very first day I've ever even seen aspx, so, please bear with me...
Basically, I want to determine if a string is empty. If it is empty, then I don't want anything to output, if it's not, then I want to output the string itself.
<%= o_handler.renderDDesc()%> //This is the string itself... If this is empty, then I want I want nothing to print
I tried:
<%if (o_handler.renderDDesc().length() > 0) { %>
<%= o_handler.renderDDesc()%>
<%}%>
But, that didn't seem to do anything. I didn't get an error, but it also didn't appear?
<%
string desc = o_handler.renderDesc();
if (!String.IsNullOrEmpty(desc)) {
Response.Write(desc);
}
%>
<%= !String.IsNullOrEmpty(o_handler.renderDDesc()) ? o_handler.renderDDesc() : ""%>
I would simply use a ternary operator as follows:
<%=( o_Handler.IsNullOrEmpty() ? string.Empty : o_handler.renderDDesc() ); %>

Resources