Search code examples
c#asp.net-mvcasp.net-mvc-4code-firstrazor-2

When using MVC code first with data annotations how do you include html markup in the display name?


I am converting a paper form into a MVC 4 web form. I have questions that are a paragraph worth of text that include superscript numbers that link to footnotes. This is what I am trying to do:

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

After creating the model I generated the controller and related views. Everything works except the html markup in the display name is converted into html encoded text (i.e. &lt;sup&gt;1&lt;/sup&gt;). The code in the view.cshtml used to display the property is just the automatically generated code:

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

I am trying to figure out how to get the html markup for the footnotes to work properly or is my approach somehow wrong and I should be doing it a different way? This is my first MVC project and I am coming from an asp.net background.


Solution

  • I think you should try to move your HTML text to resources and apply for your model the next code:

    public class PaperFormModel
    {    
        [Display(ResourceType = typeof(PaperFormModelResources), Name = "Question1FieldName")]
        public string Question1 { get; set; }
    
        // more properties go here ...
    }
    

    To create resource file:
    - Create Resources folder in your solution if it does not exist.
    - Right click on this folder in solution explorer -> Add -> Resource file or ... -> Add -> New item and select resource file
    - Name this file PaperFormModelResources
    - Add new entry with name Question1FieldName and with value 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. using resource manager.

    EDITS: If, as result, your html markup is not displayed correctly (it is just displayed as plain text) you can use the answer for this question that is:

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

    Hope it helped.