7

我有一个 MVC3 C#.Net 网络应用程序。我正在循环一个数据表。有些行导入正常,有些行不正常。我想以列表格式将错误列表发送回视图。我将以下文本分配给 ViewBag 属性

Input error on Row(1) Cell(3) Input string was not in a correct format.<br/> Input error on Row(4) Cell(3) Input string was not in a correct format.<br/>

我希望 br 会在 HTML 中写一个换行符。它不是。我希望错误消息看起来像这样

Input error on Row(1) Cell(3) Input string was not in a correct format.
Input error on Row(4) Cell(3) Input string was not in a correct format.

有任何想法吗?

4

4 回答 4

14

当您投入视野时,请使用

@Html.Raw(ViewBag.Test)

代替

@ViewBag.Test

这将向编译器表明字符串是 html 并且不需要这样编码。

于 2012-02-08T17:39:14.720 回答
8

Use a string[] to hold your errors. That way they are a well-formed and distinct set of errors instead of just one long string.

In your Controller, initializing the ViewBag property:

ViewBag.Errors = new string[] { "First error", "Second error" };

In your View, displaying these errors:

@foreach (string error in ViewBag.Errors)
{
    @Html.Label(error)
    <br />
}

Separation Of Concerns

You shouldn't be handling markup layout within your Controller (i.e. line breaks, or any other DOM elements). The presentation should be handled solely by the View. Which is why it would be best to pass a string[].

于 2012-02-08T17:36:23.587 回答
0

这对我有用:

控制器:

 ViewBag.Msg += Environment.NewLine + "xxxx";

看法:

<p class="@ViewBag.MsgColor">
        @Html.Raw(@ViewBag.Msg.Replace(Environment.NewLine, "<br/>"))
 </p>
于 2019-10-01T08:33:20.203 回答
0

我的首选方法是<br />在控制器代码中简单地将 a 添加到行时间作为 ViewData["msg"] 然后可以从剃刀页面中拉出,如下所示。

控制器代码:

ViewData["msg"] = "Your Query <br /> has been processed.";

剃刀形式代码:

@Html.Raw(@MsgFormatted)
于 2021-04-09T16:39:38.667 回答