简体   繁体   中英

ASP.NET: Bold parts of text using HtmlGenericControl

I am a complete ASP.NET newbie, so this will probably be simple.

I have a label which text is set dynamically in the code behind using the following pseudo code

label.Text = string.Format(SOME-DYNAMIC-MESSAGE(ID,1), name, day);

The SOME-DYNAMIC-MESSAGE has a form of, where {0} and {1} refers to variables name and day.

Hello {0}, today is {1}.

I need to make those variables bold . I am trying to wrap them in span, so I can access them from CSS using this code

HtmlGenericControl bold = new HtmlGenericControl("span");
    bold.InnerText = name;
    bold.Attributes.Add("class", "bold");

label.Text = string.Format(SOME-DYNAMIC-MESSAGE(ID,1), bold, day);

but it doesn't work, no extra wrapper added. It even stopped to show me the the content of the variable.

Anybody knows how to fix this?

尝试:

label.Text = string.Format(SOME-DYNAMIC-MESSAGE(ID,1), "<span style=\"font-weight:bold\">" + bold + "</span>", "<span style=\"font-weight:bold\">" + day + "</span>");

Here is a quick sample app (Console app) to demonstrate an approach. I think you are trying to format the input string for String.Format and make the font-weight of the token ( {0} , {1} , etc...) bold .

use this Func<string,string> to format the input string. then add the following CSS to your html page:

class Program
{
    static void Main(string[] args)
    {
        var input = @"Hello {0}, today is {1}.";

        Func<string, string> SomeDynamicMessage = s => {
            var val = s;
            val = val.Replace("{", "<span class='bold-token'>{");
            val = val.Replace("}", "}</span>");
            return val;
        };

        Console.WriteLine(SomeDynamicMessage(input));

        // output: Hello <span class='bold-token'>{0}</span>, today is <span class='bold-token'>{1}</span>.
        var final = Console.ReadLine();
    }
}

Css snippet:

.bold-token { font-weight: bold; }

Final output:

Hello <span class='bold-token'>{0}</span>, today is <span class='bold-token'>{1}</span>

EDIT -- MORE INFO

Here is how you should use it:

var input = @"Hello {0}, today is {1}.";
label.Text = string.Format(SomeDynamicMessage(input), "test", "Thursday");

and the output would be:

Hello <span class='bold-token'>test</span>, today is <span class='bold-token'>Thursday</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM