asp.net-mvc arrays actionlink routes

ASP.NET MVC-Pase objeto de matriz como un valor de ruta dentro de Html.ActionLink(...)



asp.net-mvc arrays (6)

Esta es una matriz de resolución de Ayuda y problemas de propiedades de IEnumerable:

public static class AjaxHelperExtensions { public static MvcHtmlString ActionLinkWithCollectionModel(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 { var value = property.GetGetMethod().Invoke(model, null) == null ? "" : property.GetGetMethod().Invoke(model, null).ToString(); if (!string.IsNullOrEmpty(value)) rv.Add(property.Name, value); } } return System.Web.Mvc.Ajax.AjaxExtensions.ActionLink(ajaxHelper, linkText, actionName, rv, ajaxOptions, htmlAttributes); } }

Tengo un método que devuelve una matriz (cadena []) y estoy tratando de pasar esta matriz de cadenas a un enlace de acción para que cree una cadena de consulta similar a:

/Controller/Action?str=val1&str=val2&str=val3...etc

Pero cuando paso el nuevo {str = GetStringArray ()} obtengo el siguiente url:

/Controller/Action?str=System.String%5B%5D

Básicamente, está tomando mi cadena [] y ejecutando .ToString () para obtener el valor.

¿Algunas ideas? ¡Gracias!


Esto realmente me molestó, así que con la inspiración de Scott Hanselman escribí el siguiente método de extensión (fluido):

public static RedirectToRouteResult WithRouteValue( this RedirectToRouteResult result, string key, object value) { if (value == null) throw new ArgumentException("value cannot be null"); result.RouteValues.Add(key, value); return result; } public static RedirectToRouteResult WithRouteValue<T>( this RedirectToRouteResult result, string key, IEnumerable<T> values) { if (result.RouteValues.Keys.Any(k => k.StartsWith(key + "["))) throw new ArgumentException("Key already exists in collection"); if (values == null) throw new ArgumentNullException("values cannot be null"); var valuesList = values.ToList(); for (int i = 0; i < valuesList.Count; i++) { result.RouteValues.Add(String.Format("{0}[{1}]", key, i), valuesList[i]); } return result; }

Llamar así:

return this.RedirectToAction("Index", "Home") .WithRouteValue("id", 1) .WithRouteValue("list", new[] { 1, 2, 3 });


Hay una biblioteca llamada Unbinder , que puede usar para insertar objetos complejos en rutas / urls.

Funciona así:

using Unbound; Unbinder u = new Unbinder(); string url = Url.RouteUrl("routeName", new RouteValueDictionary(u.Unbind(YourComplexObject)));


Intenta crear un RouteValueDictionary con tus valores. Tendrás que darle a cada entrada una clave diferente.

<% var rv = new RouteValueDictionary(); var strings = GetStringArray(); for (int i = 0; i < strings.Length; ++i) { rv["str[" + i + "]"] = strings[i]; } %> <%= Html.ActionLink( "Link", "Action", "Controller", rv, null ) %>

le dará un enlace como

<a href=''/Controller/Action?str=val0&str=val1&...''>Link</a>

EDITAR : MVC2 cambió la interfaz ValueProvider para hacer obsoleta mi respuesta original. Debe usar un modelo con una matriz de cadenas como una propiedad.

public class Model { public string Str[] { get; set; } }

Luego, la carpeta modelo rellenará su modelo con los valores que pase en la URL.

public ActionResult Action( Model model ) { var str0 = model.Str[0]; }


Otra solución que me vino a la mente:

string url = "/Controller/Action?iVal=5&str=" + string.Join("&str=", strArray);

Esto está sucio y debes probarlo antes de usarlo, pero debería funcionar de todos modos. Espero que esto ayude.


Yo usaría POST para una matriz. Además de ser feo y un abuso de GET, te arriesgas a quedarte sin espacio para URL (lo creas o no).

Suponiendo un límite de 2000 bytes . La sobrecarga de cadena de consulta (& str =) lo reduce a ~ 300 bytes de datos reales (suponiendo que el resto de la URL es 0 bytes).