Adding a class to #Html.Raw helper that uses TempData? - c#

I suppose the issue is that Html.Raw doesn't have an overload option (which makes sense, since you'd just declare the class in one of the opening tags in the raw html), but also that I have a TempData element to deal with..
Here's what I have (I've tried a few different combinations, with ', ", #, +, etc.):
#Html.Raw("<div class='"logout"'>#'"TempData["logoutText"]"'</div>")
Is what I'm trying to do even possible with Html.Raw?

Try this
#Html.Raw("<div class=\"logout\">" + TempData["logoutText"] + "</div>")

The following should work for you:
#Html.Raw("<div class='" + logout + "'>" + TempData["logoutText"] + "</div>")
However a cleaner solution would be:
#Html.Raw(string.Format("<div class='{0}'>{1}</div>", logout, TempData["logoutText"]))

#Html.Raw("<div class='" +logout+"'>'"+ TempData["logoutText"] +"'</div>")
If the variable logout = "logout"
and TempData["logoutText"] = "Click Here To LogOut"
Then the output would be
<div class='logout'>'Click Here To LogOut'</div>
You can also use a formatter like below
#Html.Raw(string.Format("<div class='{0}'>{1}</div>",logout, TempData["logoutText"]))

Related

C# Razor The name does not exist in the current context

I know I must be being stupid here, but I can't work out why this code isn't working. I'm very new to Razor, so please go easy on me.
I have the following code in my markup: (I've cut it down to be as simple as I can make it while still reproducing the issue so that I can hopefully diagnose the issue easier)
string testVar = "test";
#testVar
It returns the following:
error CS0103: The name 'testVar' does not exist in the current context
I've tried using different names for the variable, I've tried having it use "var" instead of "string" for it's declaration, I've tried assigning various different values to it, I've tried surrounding the variable in brackets like #(testVar), but the issue is still there. It's very frustrating, because in another part of my code I have
string prop = #p.Name + " (" + #p.PropertyType + ") - " + #p.GetValue(#page, null).ToString() + "\r\n";
#prop
which works fine.
I can't think what could be causing it, and it's starting to frustrate me.
Thanks,
YM
In Razor when we want to write c# statements we have to tell it that from here c# code starts:
#{ // from here c# block starts
string testVar = "test";
} // here ends
Now if you want to access this variable in html you can do like this:
<span>#testVar</span>
When you are writing:
string prop = #p.Name + " (" + #p.PropertyType + ") - " + #p.GetValue(#page, null).ToString() + "\r\n";
it is considered as plain text and will be rendered on browser like "string prop = ..."
you have to tell that it is c# code by following way:
#{
string prop = #p.Name + " (" + #p.PropertyType + ") - " + #p.GetValue(#page, null).ToString() + "\r\n";
}

Alert not popping up for string ASP.Net

I'm stuck again with alertboxes!
This works like a charm:
Response.Write("<script>alert('" + "Hello"+ "');</script>");
result is a string. I need to display that. This is where my problem comes in. This doesn't popup:
Response.Write("<script>alert('" + result + "');</script>");
I am passing result across many layers. Also I have used this format in all pages. Don't want a message box. Or a modal popupwindow. I want this.
I checked online and according to the syntax, it is supposed to work! Please help!
To put any value in a Javascript string literal, you need to escape apostrophes (as they are used as the delimiter for the string) and backslashes:
Response.Write(
"<script>" +
"alert('" + result.Replace("'", "\\'").Replace("\\", "\\\\") + "');" +
"</script>"
);
Try this
Response.Write("<script type='text/javascript'>alert('"+result+"')</script>")
Try this
String message = String.format({0}{1}{2},
"<script type='text/javascript'>alert('",
result,
"')</script>");
Response.Write(message);
Response.Write("<script> alert('" + HttpUtility.HtmlEncode(result) + "'); </script>")

C# Append Newline To <p> tags in HTML fragment

I've done this but it feels dirty and wrong. What are some better alternatives?
private static string addNewLinesToStoryParagraphs(string story)
{
string result = story.Replace("</p>", "</p>" + Environment.NewLine);
result = result.Replace("</p>" + Environment.NewLine + Environment.NewLine, "</p>" + Environment.NewLine);
return result;
}
The input string is an HTML fragment serialized to a string. I want to make sure there is a new line for every <p></p> pair. Obviously if the NewLine already exists I don't want to have two lines between each <p></p> pair.
I briefly looked at trying something with the HTML Agility Pack, but I didn't see any save overload or options for cleaning up HTML. I've got very little experience with that library however so if there is a way to do it I'm all ears.
Regex.Replace(input,"</p>(?![\n\r]+)","</p>"+Environment.NewLine);

Html tags shows as it is in page when formatted from c# code

I am trying to format a string to add spaces in between the strings in c#.
summary.AppendFormat(" {0} {1}: {2}{3}</br> ", item.FirstName, item.LastName, item.Completed ? item.Summary : "not completed", item.Schedule == DateTime.MinValue ? "" : " (" + DateTime.ToShortDate(item.Schedule, user) + ")");
This should render in the HTML page as
First Round Suri Narayanan: recommend (3/2/2012)
but i am seeing this as like below in html page
First Round</br> Suri Narayanan: recommend (3/2/2012)</br>
if i edit the same using firebug, say if i put some space, then its getting formatted well and good.
Please let me know your comments on this.
You should use Literal like below.
<asp:Literal ID="Literal" runat="server" Mode="PassThrough"></asp:Literal>
Literal.text = "Your text"

String concatenation doesn't seem to work in C#

I don't know what is wrong with the following string:
"Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
I can't get the concatenated string. I am getting Report(29-Dec-2009. That's all and
the rest gets left out from the string.
What is the reason?
Try this:
string filename =
String.Format(
"Report({0:dd-MMM-yyyy} to {1:dd-MMM-yyyy})",
System.DateTime.Now, System.DateTime.Now.AddMonths(-1));
EDIT: Since in your download box you got your filename broken in first whitespace, you could to try ONE of these:
filename = HttpUtility.UrlEncode(filename); // OR
filename = """" + filename + """";
Seems some browsers doesn't handles whitespaces very nicely: Filenames with spaces are truncated upon download. Please check it you can to download other filenames with whitespace in other sites.
You need to assign it to something:
string s = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
Update: I just saw your update to the question. How are you displaying the string? I'm guessing that you are displaying it in a GUI and the label is too short to display the complete text.
Try this:
string newstring =
string.Format(
"Report ({0} to {1})",
System.DateTime.Now.ToString("dd-MMM-yyyy"),
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
);
What are you assigning the result to? It would be easier to read the code if you used string.Format
You are not assigning the concatenated result to anything, so can't use it:
string myConcatenated = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + ")";
Using this code...
string test = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " +
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")";
I saw the following result.
Report(29-Dec-2009 to 29-Nov-2009)
It could be that the string is being truncated later on. Make sure that you set a breakpoint right after this code is run and check the value of the variable to which it is assigned (test in my case).
If, as in your previous question, you are using this value to create a file, it may be that it's the space before "to" that is causing the problem. Try to use:
"Report("
+ System.DateTime.Now.ToString("dd-MMM-yyyy")
+ "To"
+ System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
+ ")"
instead and see if that fixes it.
If that does fix it, you'll probably need to either figure out how to quote the entire file name so it's not treated as the three separate arguments, "Report(29-Dec-2009", "to" and "29-Nov-2009)". Or simply leave your reports names without spaces.
I'd choose the latter but then I'm fundamentally opposed to spaces in filenames - they make simple scripts so much harder to write :-)

Categories