Skip to content Skip to sidebar Skip to footer

Passing Ienumerable Property In Routevalues Of Actionlink

Imagine an object defined like : public class MyViewModel{ public List MyList { get; set; } } In my view, i have this Action link : @Ajax.ActionLink('<', 'Ind

Solution 1:

You can try string.Join. Something like this

@Ajax.ActionLink(
            "Your text", -- <
            "ActionName", -- Index
            new
            {
               MyList =string.Join(",", new List<string>() {"foo", "bar"}),
              otherPropertiesIfyouwant = YourValue
            }, -- rounteValues
            new AjaxOptions { UpdateTargetId = "..." }, -- Your Ajax option --optional
            new { @id = "back" } -- Your html attribute - optional
            )   

Solution 2:

With Stephen's anwser, i have develop a helper extension method to do this.

Be careful of the URL query string limit : if the collection has too many values, the URL can be greater than 255 characters and throw an exception.

publicstaticclassAjaxHelperExtensions
{
    publicstatic MvcHtmlString ActionLinkUsingCollection(this AjaxHelper ajaxHelper, string linkText, string actionName, object model, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
    {
        var rv = new RouteValueDictionary();
        foreach (var property in model.GetType().GetProperties())
        {
            if (typeof(ICollection).IsAssignableFrom(property.PropertyType))
            {
                var s = ((IEnumerable<object>)property.GetValue(model));
                if (s != null && s.Any())
                {
                    var values = s.Select(p => p.ToString()).Where(p => !string.IsNullOrEmpty(p)).ToList();
                    for (var i = 0; i < values.Count(); i++)
                        rv.Add(string.Concat(property.Name, "[", i, "]"), values[i]);
                }
            }
            else
            {
                varvalue = property.GetGetMethod().Invoke(model, null) == null ? "" : property.GetGetMethod().Invoke(model, null).ToString();
                if (!string.IsNullOrEmpty(value))
                    rv.Add(property.Name, value);
            }
        }
        return AjaxExtensions.ActionLink(ajaxHelper, linkText, actionName, rv, ajaxOptions, htmlAttributes);
    }
}

Post a Comment for "Passing Ienumerable Property In Routevalues Of Actionlink"