How to render HtmlAttributes using object values ​​using ASP.NET MVC 3 Razor?

I am trying to display the following HTML using MVC3 Razor View:

<input id="EffectiveDate" name="EffectiveDate" type="date" data-options='{"mode": "flipbox"}' />

I was unable to get quotes in the data-options attribute for rendering. No matter what I try to do, they appear as&quot;

Here are a few of the many approaches I've tried in my view:

@Html.TextBoxFor(model => model.EffectiveDate, new { type = "date", data_options= " { 'mode':'flipbox' }"})

and

@Html.TextBoxFor(model => model.EffectiveDate, new { type = "date", data_options= @Html.Raw("{\"mode\":\"flipbox\"}")})

Any suggestions on how to decode quotes?

+5
source share
2 answers

, MVC Editor. "EditorTemplates" "Views\Shared". DateTime.cshtml EditorTemplates.

EditorFor() , ( , EffectiveDate DateTime):

@Html.EditorFor(m => m.EffectiveDate)

DateTime.cshtml :

@model System.DateTime
@{
    var id = this.ViewData.TemplateInfo.GetFullHtmlFieldId("");
    var name = this.ViewData.TemplateInfo.GetFullHtmlFieldName("");
}
<input id="@id" name="@name" type="date" data-options='{"mode": "flipbox"}' />

, .

+4

: MVC (.. TextBoxFor). , TagBuilder, HtmlHelper, HtmlEncode . TagBuilder:

private void AppendAttributes(StringBuilder sb)
{
    foreach (var attribute in Attributes)
    {
        string key = attribute.Key;
        if (String.Equals(key, "id", StringComparison.Ordinal /* case-sensitive */) && String.IsNullOrEmpty(attribute.Value))
        {
            continue; // DevDiv Bugs #227595: don't output empty IDs 
        }
        string value = HttpUtility.HtmlAttributeEncode(attribute.Value);
        sb.Append(' ')
            .Append(key)
            .Append("=\"")
            .Append(value)
            .Append('"');
    }
} 

, , JavaScript. jQuery, :

var value = $('<textarea/>').html(yourElement.data('options')).val();

, .

:

+1

All Articles