c# - 当首先使用带有数据注释的 MVC 代码时,如何在显示名称中包含 html 标记?

标签 c# asp.net-mvc asp.net-mvc-4 code-first razor-2

我正在将纸质表单转换为 MVC 4 Web 表单。我的问题是一段文本,其中包含链接到脚注的上标数字。这就是我正在尝试做的事情:

public class PaperFormModel
{
    [Display(Name = "Full paragraph of question text copied straight 
         off of the paper form<a href="#footnote1"><sup>footnote 1</sup></a> 
         and it needs to include the properly formatted superscript 
         and/or a link to the footnote text.")]
    public string Question1 { get; set; }

    // more properties go here ...
}

创建模型后,我生成了 Controller 和相关 View 。除了显示名称中的 html 标记被转换为 html 编码文本(即 1)之外,一切正常。 view.cshtml中用于显示属性的代码只是自动生成的代码:

<div class="editor-label">
    @Html.LabelFor(model => model.Question1)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Question1)
    @Html.ValidationMessageFor(model => model.Question1)
</div>

我试图弄清楚如何让脚注的 html 标记正常工作,或者我的方法是否有问题,我应该采取不同的方式?这是我的第一个 MVC 项目,我有 ASP.NET 背景。

最佳答案

我认为您应该尝试将 HTML 文本移动到资源并为您的模型应用下一个代码:

public class PaperFormModel
{    
    [Display(ResourceType = typeof(PaperFormModelResources), Name = "Question1FieldName")]
    public string Question1 { get; set; }

    // more properties go here ...
}

创建资源文件:
- 创建Resources解决方案中的文件夹(如果不存在)。
-Right click on this folder in solution explorer -> Add -> Resource file... -> Add -> New item并选择resource file
- 将此文件命名为PaperFormModelResources
- 添加名称为 Question1FieldName 的新条目并具有值 Full paragraph of question text copied straight off of the paper form<a href="#footnote1"><sup>footnote 1</sup></a> and it needs to include the properly formatted superscript and/or a link to the footnote text.使用资源管理器。

编辑: 如果您的 html 标记未正确显示(仅显示为纯文本),您可以使用 this question 的答案。即:

<div class="editor-label">
    @Html.Raw(HttpUtility.HtmlDecode(Html.LabelFor(model => model.Question1).ToHtmlString))
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Question1)
    @Html.ValidationMessageFor(model => model.Question1)
</div>

希望有帮助。

关于c# - 当首先使用带有数据注释的 MVC 代码时,如何在显示名称中包含 html 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823512/

相关文章:

c# - 在 C# 中查找和删除元组列表中的重复项

c# - Entity Framework 和业务对象

asp.net-mvc - 如何在 MVC 2 的双向绑定(bind) View 中格式化日期?

c# - MVC XML 模型作为另一个模型的属性

asp.net-mvc-4 - 具有 bool 字段自定义的剑道网格过滤器

c# - 使用 Excel 作为日志阅读器。如果 Excel 打开,如何写入日志文件?

c# - 使用 'AsParallel()'/'Parallel.ForEach()' 指针?

c# - Visual Studio 自动格式化没有正确格式化我的 Razor 代码

c# - ASP.NET MVC 路由和类似 URL 的 Slug

asp.net - MVC 中同一页面上有多个 ViewModel