[RESOLVED]using dataannotations on dictionaries.

Hi

I have a simple question: Is it posible to use the display-attribute and other dataannotations on a dictionarys key- and value-part respectively?

i guess you cannot. i tried using web.config value, it gave me an error, "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type". I did not try resource values or dictionary.

It sounds like I should create a new model class having the key and value and use that in an IList instead.

the error specifically said constant values. I guess you wont able to use IList or Dictionary. Because they have to instantiated and filled with values. There could be some advanced concept like extending any of default MVC classes like the controller or
model binder or data provider to do that for you. But i havent come across anything.

Hi

I’ve been doing some experiments, and it seems that you can use the DisplayAttribute on IList.

I created two models:

public class Model1
    {       
        [Display(Name = "List of Capitals")]
        public IList<Model2> Capitals { get; set; }

    }

 public class Model2
    {
        [Display(Name="Name of capital")]
        public string CapitalName { get; set; }

        [Display(Name = "Name of country")]
        public string CountryName { get; set; }
    }

and used Model1 inside a view:

@using MvcApplication2.Models;
@model Model1
@{
    ViewBag.Title = "Home Page";
}

@using (@Html.BeginForm("VisFil", "Home", FormMethod.Post, new { enc = "multipart/form-data" }))
{    
    <div>
        @if(Model.Capitals!=null && Model.Capitals.Count>0)
        { 
        <table>
            <thead>
                <tr>
                    <th colspan="2">@Html.DisplayNameFor(x => x.Capitals)</th>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(x => x.Capitals[0].CapitalName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(x => x.Capitals[0].CountryName)
                    </th>
                </tr>

            </thead>
            <tbody>
                @foreach (Model2 item in Model.Capitals)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(x => item.CapitalName)
                        </td>
                        <td>
                            @Html.DisplayFor(x => item.CountryName)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        }
        
    </div>
}

The result came out like this:

Table of capitals

Leave a Reply