Using ASP.NET MVC v2 EditorFor and DisplayFor with IEnumerable Generic types

后端 未结 6 795
情话喂你
情话喂你 2020-12-07 22:51

I have a IList as a property named Tags in my model. How do I name the files for display and editor templates to respect it when I call

6条回答
  •  执念已碎
    2020-12-07 23:24

    You could create a custom collection type and name the editor to match that.

    Assuming you created custom collection called Tags you could change your model to:

    class MyModel
    {
       Tags Tags { get; protected set;}
    }
    

    Then you would name your editor and display templates Tags.ascx.

    Which would make your view code work like you wanted:

    <%= Html.EditorFor(t => t.Tags) %>
    

    For the custom collection you basically just create a wrapper around an implementation of a generic collection and expose it's methods and properties:

    public class Tags : IList
    {
        //Use a private List to do all the 
        //heavy lifting.
        private List _tags;
    
        public Tags()
        {
            _tags = new List();
        }
    
        public Tags(IEnumerable tags)
        {
            _tags = new List(tags);
        }
    
        #region Implementation of IEnumerable
    
        public IEnumerator GetEnumerator()
        {
            return _tags.GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _tags.GetEnumerator();
        }
    
        #endregion
    
        #region Implementation of ICollection
    
        public void Add(Tag tag)
        {
            _tags.Add(tag);
        }
    
        public void Clear()
        {
            _tags.Clear();
        }
    
        public bool Contains(Tag tag)
        {
            return _tags.Contains(tag);
        }
    
        public void CopyTo(Tag[] array, int arrayIndex)
        {
            _tags.CopyTo(array, arrayIndex);
        }
    
        public bool Remove(Tag tag)
        {
            return _tags.Remove(tag);
        }
    
        public int Count
        {
            get { return _tags.Count; }
        }
    
        public bool IsReadOnly
        {
            get { return false; }
        }
    
        #endregion
    
        #region Implementation of IList
    
        public int IndexOf(Tag tag)
        {
            return _tags.IndexOf(tag);
        }
    
        public void Insert(int index, Tag tag)
        {
            _tags.Insert(index, tag);
        }
    
        public void RemoveAt(int index)
        {
            _tags.RemoveAt(index);
        }
    
        public Tag this[int index]
        {
            get { return _tags[index]; }
            set { _tags[index] = value; }
        }
    
        #endregion
    }
    

提交回复
热议问题