First off, forgive me for I know very little about MS Visual Studio & ASP, but my issue is that I can not seem to figure out the syntax for placing a variable within a string in the following ASP code....
description = viewCat[0]["description"].ToString();
metaHTML = #"
<title></title>
<meta name='description' content='" + description + "' />
";
Question I'm looking for is what is the correct way of placing the variable "description" within the string??
To create a string from a variable, you can use String.Format:
string description = "something";
string formattedStr = String.Format("Some string and {0}",description);
In your case:
description = viewCat[0]["description"].ToString();
metaHTML = String.Format("<title></title><meta name='description' content='{0}'/>", description);
Your assignment of metaHTML comprises three strings - two literals and the variable description. Only the first literal is a multiline string (you prefix it with #). The second string is not: the characters "' /> are an unterminated string, and aren't correlated with the characters on the next line.
What you want to do is this - note the extra #:
metaHTML = #"
<title></title>
<meta name='description' content='" + description + #"' />
";
What is the error that you get since this is a nice way of doing the stuff that you're talking about.
#"<title></title>
<meta name='description' content='" + description + "' />";
The only thing that you must worry about is any un escapted " inside the string. On the first occurance this string would break the string. Otherwise it would work.
Red squiggly lines in VS
In the Visual Studio the Red Squiggly lines are due to the error in the String length. In ASP.NET and C# to create multiline Strings you use # before the string to make it multiline. Like the first line of your String value.
Otherwise each string is single line and you cannot start a new line in it like you're doing right now. So either use this
<meta name='description' content='" + description + "' />";
... or else use this
<!-- note the # in the string -->
<meta name='description' content='" + description + #"' />
";
The better function is to use the first code I provided, because it ends the line where it must be ended. Try it, it would remove the red lines.
Related
I would like for C# to detect the variables in my mailbody and replace them with the values each of them already has in my method.
I'm saving my mails in a TEXT datatype in mysql
This is what i save into my Text:
<html>
<h1>
<span style='text-decoration: underline;'>
<strong>Solicitud</strong>
</span>
</h1>
<br/>" + "<body>Blabla" + user.Nombre + " " + user.Apellido + " p<br/>La razón a que: <br />"+ razon+ ".</body>
</html>
I want it to replace user.Nombre user.Apellido and razon which are variables already available in the method
For example if my method has:
user.Nombre = "MATT";
user.Apellido ="CASA";
razon = "why not?";
Then detecting the variables i would have:
<html>
<h1>
<span style='text-decoration: underline;'>
<strong>Solicitud</strong>
</span>
</h1>
<br/>" + "<body>Blabla" + "MATT"+ " " + "CASA" + " p<br/>La razón a que: <br />"+ "Why not?"+ ".</body>
</html>
The problem is making C# detect that the string already has variables inside of it.
If I understand your question correctly, which is pretty hard given then English you have used.
You want to replace a parts of a string you retrieved from a database?
You can perform string replacements like the below example.
string email = emailAsString.Replace("+ user.Nombre +", variable1);
You can read more on this here, if you so wish.
String Replace - https://www.dotnetperls.com/replace
Well searched far and wide in the web, there is a method to compile manually but its highly dangerous so I decided to use String.Format , and the templates of my mails swap the "+ variable +" to {#}
Interpolating a string stored in a database
After retrieving use:
var formatedString= String.Format(string , variables);
I am trying to insert New Line after word car but it is not working with folowing solution
Char(13) - not working
Environment.NewLine - when i use this it works but appends '(' this char in sql rows like 'Car ( Rate:2CR'
\n\r - not working
Code:
cmd.Parameters.AddWithValue("#ColumnCar", Car + "char(13)" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + "\n\r" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + Environment.NewLine + "Rate:2CR";
cmd.ExecuteNonQuery();
Need output in sql table ColumnCar row value as follows:
Car
Rate:2cr
Note : here after Car there will be a newline and then Rate:2Cr will be added
With the LoC Car + "char(13)" + "Rate:2CR"; you will get a literal string "char(13)" between your 2 values, not a new line. If you want only a new line you can append "\n" or you can append the character equivalent (char)10 of new line.
Now what character or string actually represents a new line might depend on your environment including the collation you are using. In simple ascii/ansi this will work. It might not be the same for another collation. As #mhasan pointed out it could also be different depending on the O/S.
Using characters
const char carriageReturn = (char) 13; // see https://en.wikipedia.org/wiki/Carriage_return
const char newLine = (char) 10;
var car = "some car";
var toInsert = car + newLine + "Rate:2CR";
cmd.Parameters.AddWithValue("#ColumnCar", toInsert);
This would also work and produce the same result:
var toInsert = car + "\n" + "Rate:2CR";
Use combination of newline and carriage return characters i.e. char(13) + char(10) for inserting new line in windows OS system.
For MAC its \r char(13) , for Linux its \n i.e. char(10) but for windows its combination of both.
Try this code hope its working...
Make a string variable and store all value in variable..
ex: string abc=textbox1.text+" "+"Rate:2cr";
#ColumnCar=abc.tostring();
now put your code
cmd.Parameters.AddWithValue("#ColumnCar",datatype);
cmd.executenonquery();
The following code works fine with unicode fields in a MS SQL-Server 2016 DB :
string carString = $"Volvo{Environment.NewLine}Rate: 2CR";
SqlParameter parameter = new SqlParameter("#ColumnCar", carString);
command.Parameters.Add(parameter);
The '(' when you use Environment.NewLine must be another error somewhere else. What is Car in your code? A class instance? What does its ToString() expand to?
Don't use string1 + " " + string2 concatenation.
Use string.Format(), $"" - inline syntax (like above) or StringBuilder to build your strings.
If i have an image tooltip that is being populated from a database table. I am generating this html below from my server side C# code
public string GetImage()
{
return "<img class='iconSpace' title ='" + dataIssue + "' src='/Content/Images/Icons" + size + "/information_red.png' />";
}
the issue is that if the variable dataIssue has an apostrophe in it, it only shows the characters in the string up to that point.
What is the best way to show the whole string in the tooltip given the code above?
' is not special symbol for HTML, and browser shows whole string without problems, but you can have problems with following symbols " < > & they should be escaped as:
"
<
>
&
if your browser treats HTML standard incorrectly and cut the rest of the string, you can try to escape single quote with ' - this will work for all browsers
so, according HTML standard attribute values should be surrounded by " symbol, not by ', so the problem here should be solved:
dataIssue = any_kind_of_html_escape_function_here(dataIssue);
return "<img class=\"iconSpace\" title=\"" + dataIssue + "\" src=\"/Content/Images/Icons" + size + "/information_red.png\" />";
For asp.net htmlencode function is defined here: http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx
Would this work for you?
string img = "<img class=\"iconSpac\" title=\"" + dataIssue + "\" " + "scr=\"/Content/Images/Icons\"" + size + "/information_red.png\" />";
You should use HttpUtility.HtmlEncode("...") for it.
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx
while (reader.Read())
{
sb2.Append("<a href=" + "Doc/" + reader[1].ToString() + "
target=_blank style=text-decoration:none; color:#000;>" + reader[0].ToString() + "</a><img src=images/new1.gif> </img><hr />");
}
/* for example
i want to save image name abhi shek.jpg but these hyperlink only get abhi after space not
get anything pls solve these problem */
The reason that the attribute is cut at the space is that you don't have quotation marks around the value. What comes after the space becomes a different attribute. You should have quotation marks around the other attribute values also. If you don't have them around the style value, the color won't be part of the style.
Also, spaces in an URL is invalid, you need to encode the name.
sb2.Append("" + reader[0].ToString() + "<img src=\"images/new1.gif\"> </img><hr />");
How can I escape the Quotes so that this statement
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+""");combo.showDropDown(true);}</script>";
reads like this
function ShowDropDown() {
var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox");
combo.showDropDown(true);
}
EDIT- UPDATE
I might of asked the question wrong because i keep getting different errors. If I put the javascript directly on the page normally the function works. When I inject the javascript this way it doesnt work
I am doing this in code behind
string sScript =#"<script language='javascript'> function ShowDropDown(){ var combo = $find("""+this.ClientID+#"""); combo.showDropDown(true); } </script>";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "autoopendropdown", sScript, false);
OnClientFocus = "ShowDropDown()";
it gets generated this way
<script language='javascript'> function ShowDropDown(){ var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox"); combo.showDropDown(true); } </script>
but the variable combo is null and thats what the problem is. I cant figure out why when it is registered with code-behind it doesnt work and when write it normally on the page it does.
Simple way: Add the same # at the beginning of the second string literal:
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+#""");combo.showDropDown(true);}</script>";
Better way: use string.Format
string sScript = string.Format(
#"<script language='javascript'>
function ShowDropDown(){
var combo = $find(""{0}"");combo.showDropDown(true);
}
</script>",
this.ClientID);
(Best way: separate concerns using unobtrusive javascript.)
string sScript = "<script language='javascript'>\n" +
"function ShowDropDown() {\n" +
" var combo = $find(""" + this.ClientID + """);\n" +
" combo.showDropDown(true);\n" +
"}\n" +
"</script>";
The escape for double quotes in C# (and most C family languages) is \"
Or you could just use single quotes since it's valid in JavaScript.
If I understand your question correctly, you want to concatenate this.ClientID with the rest of the script.
You can do this using the String.Format method like so:
string scriptFormat = #"<script language='javascript'>function ShowDropDown(){var combo = $find(""{0}"");combo.showDropDown(true);}</script>";
string sScript = String.Format(scriptFormat, this.ClientID);
Note that inside a verbatim string literal, "" produces a single " character.
You can escape them using the \ character.
For a complete list of escape combinations, see section 2.4.4.4 Character literals of the C# language specification.
NOTE: language is deprecated for script tags, use type
string sScript =#"
<script type='text/javascript'>
function ShowDropDown(){
var combo = $find(""" + this.ClientID + #""");
combo.showDropDown(true);
}
</script>";