AndrewC
AndrewC

Reputation: 461

ASP.Net MVC: Html.Editor for dictionary entries

I am trying to use @Html.Editor for dictionary entries, but I can't get it to work. I am running ASP.Net Core 1.0.

Example model:

public class TestModel
{
    public string Title { get; set; }
    public IDictionary<int, Fruit> Basket { get; set; }
}

This works fine:

@foreach (var key in Model.Basket.Keys)
{
    @Html.EditorFor(m => m.Basket[key])
}

But this does not:

@foreach (var key in Model.Basket.Keys)
{
    @Html.Editor($"Basket[{key}]")
}

In the latter the expression Basket[1] etc. is not resolved, and I always get a blank text box. If I force it to use my Fruit editor template, the model is always null.

I know it's better to use EditorFor whenever possible, but in my real, non-trivial application I am calling IHtmlHelper.Editor(expression) from inside a TagHelper... something like this:

@foreach (var key in Model.Basket.Keys)
{
    <mytaghelper for="Baskey[key]" />
}

And in the TagHelper's Process method:

if (For != null)
{
    (_htmlHelper as HtmlHelper)?.Contextualize(ViewContext);
    tag.InnerHtml.Append(_htmlHelper.Editor(For.Name));
}

Although I have the ModelExpression ("For") in the TagHelper I don't think there's another way to call Editor except as I have tried it.

Thanks for your help!

Upvotes: 2

Views: 1931

Answers (1)

Abdul Hadee
Abdul Hadee

Reputation: 113

  @Html.EditorFor(model => model.urDictionaryName["KeyValue"], new { htmlAttributes = new { @id = "yourId" } })

Or if you want it as label,you can use it as label and use hiddenfor for mapping

 @Html.Label(Model.urDictionaryName["KeyValue"])
 @Html.HiddenFor(model => model.urDictionaryName["KeyValue"], Model.maskDetails["KeyValue"])

Upvotes: 1

Related Questions