当MVC代码首先与数据注释一起使用时,如何在显示名称中包含html标记

本文关键字:显示 标记 html 包含 代码 MVC 数据 一起 注释 | 更新日期: 2023-09-27 18:07:33

我正在将一个纸质表单转换为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 ...
}

创建模型后,我生成了控制器和相关视图。除了显示名称中的html标记被转换为html编码文本(即&lt;sup&gt;1&lt;/sup&(之外,一切都正常。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背景。

当MVC代码首先与数据注释一起使用时,如何在显示名称中包含html标记

我认为您应该尝试将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标记没有正确显示(它只是显示为纯文本(,你可以使用这个问题的答案:

<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>

希望它能有所帮助。