开发者

Passing NewLine (or <Br />) inside ViewData["msg"]

How do I pass an Environment.NewLine (or a < br />) inside a ViewData["msg"] that renders as a real <br /> inside the View itself?

I'm using C# 开发者_开发问答...


You can simply use

HttpUtility.HtmlEncode("<br />");

Have a look here for further details.

EDIT:

I am sorry but I did not understand the question at the beginning. I thought you wanted to encode the passed string. Sometimes I read question too fast :)

Anyway to completely answer your question have a look at these samples. Suppose in your action you have:

[HttpGet]
public virtual ActionResult Index() {
    ViewData["Message"] = "This is a test." + "<br />" + "Does it work?";
    return View();
}

And in your view you have

<p>Sample 1: <br /><%= ViewData["Message"]%></p>
<p>Sample 2: <br /><%: ViewData["Message"]%></p>

Notice the difference between the two construct. You will get the following results:

Sample 1: 
This is a test.
Does it work?

Sample 2: 
This is a test.<br />Does it work?

So the first sample usage answer your question. The key is to simply not encoding the string as opposed to what I understood at the beginning. The second construct, the one that use <%: %>, available if you're using .NET 4.0, automatically encode every string it render.

If you still want to use this latest construct and avoid that the string would be encoded you have to use a trick. Simply tell the construct that the string is already encoded and it does not need to be re-encoded. To achieve this use this sample code

[HttpGet]
public virtual ActionResult Index() {
    ViewData["Message2"] = MvcHtmlString.Create( "This is a test." + "<br />" + "Does it work?" );
    return View();
}

and in the view normally use the <%: %> construct

<p>Sample 3: <br /><%: ViewData["Message2"]%></p>

For more details on using the MvcHtmlString and how it works please refer to this question on SO.

Ciao!


Did you try \n or \r inside the ViewData string itself?


Use this:

TempData["MsgString"] = MvcHtmlString.Create("No Data" + "<br />" + "For Something");

Or, with variables:

TempData["MsgString"] = MvcHtmlString.Create(Strings.StrNoData + "<br />" + Strings.StrSomething);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜