views:

49

answers:

1

Hello,

i have this model on mvc:

public class User
{
    public string Name
    {
      get;
      set;
    }
    public IList<string>RelatedTags
    {
      get;
      set;
    }
}

And the following typed view (user) to edit an add a user (AddEdit.aspx view):

<div>
   <%: Html.LabelFor(e => e.Name)%>
   <%: Html.TextBoxFor(e => e.Name)%>
   <%: Html.ValidationMessageFor(e => e.Name)%>
</div>
<div>
   <%: Html.LabelFor(e => e.RelatedTags)%>
   <%: Html.TextBoxFor(e => e.RelatedTags)%>
   <%: Html.ValidationMessageFor(e => e.RelatedTags)%>
</div>

For other hand i have a "RelatedTags" field. I needed (on action controller side) a List of tags related with the user that im adding. For this reason i created a Custom model binder (to take the string of the textbox and pass it as List):

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
   List<string> listoftags = bindingContext.ValueProvider.GetValue("RelatedTags").AttemptedValue.Split(',').ToList<string>();
     return listoftags;
}

Actually i can use the AddEdit.aspx to add a new user (on controller side im getting a List of related tags, but when i edit a user i dont know where i can convert this List to comma string, and either i dont know should change these lines on the view:

<div>
       <%: Html.LabelFor(e => e.RelatedTags)%>
       <%: Html.TextBoxFor(e => e.RelatedTags)%>
       <%: Html.ValidationMessageFor(e => e.RelatedTags)%>
</div>

By the moment, just in case, i created an extension method for the IList:

public static class Extensions
    {
        public static string ToCommaString<T>(this IList<T> input)
        {
            StringBuilder sb = new StringBuilder();
            foreach (T value in input)
            {
                sb.Append(value);
                sb.Append(",");
            }
            return sb.ToString();
        }
    }

Could you give me any help for when im editing a user see in the input field a string separated with commas with all the elements of the list?

Thanks a lot in advance.

Best Regards.

Jose.

+1  A: 

Maybe you could use this model?

public class UserModel
{
    public string Name { get; set; }
    protected IList<string> RelatedTagsList { get; set; } 
    public string RelatedTags
    {
        get
        {
            return string.Join(",", RelatedTagsList.ToArray());
        }

        set
        {
            RelatedTagsList = value.Split(',').ToList();
        }
    }
}

No binders and extension methods required.

LukLed
Thanks a lot!!Regards.Jose
Josemalive