gpt4 book ai didi

asp.net-mvc - 将复杂类型的数组添加到 RouteValueDictionary

转载 作者:行者123 更新时间:2023-12-01 15:37:48 32 4
gpt4 key购买 nike

我想知道是否有一种优雅的方法可以将复杂类型的数组添加到 RouteValueDictionary 或兼容类型?

例如,如果我有一个类和一个 Action :

public class TestObject
{
public string Name { get; set; }
public int Count { get; set; }

public TestObject()
{
}

public TestObject(string name, int count)
{
this.Name = name;
this.Count = count;
}
}

public ActionResult Test(ICollection<TestObjects> t)
{
return View();
}

然后我知道如果我通过 URL "/Test?t[0].Name=One&t[0].Count=1&t[1].Name=Two&t[1].Count=2"调用这个 Action ,MVC 将映射那些查询字符串参数自动回到 ICollection 类型。但是,如果我使用 Url.Action() 在某处手动创建链接,并且我想传递参数的 RouteValueDictionary,当我将 ICollection 添加到 RouteValueDictionary 时,Url.Action 只会将其呈现为类型,例如 &t= System.Collections.Generic.List。

例如:
RouteValueDictionary routeValDict = new RouteValueDictionary();
List<TestObject> testObjects = new List<TestObject>();

testObjects.Add(new TestObject("One", 1));
testObjects.Add(new TestObject("Two", 2));
routeValDict.Add("t", testObjects);

// Does not properly create the parameters for the List<TestObject> collection.
string url = Url.Action("Test", "Test", routeValDict);

有没有办法让它自动将该集合呈现为 MVC 也理解如何映射的格式,或者我必须手动执行此操作?

我错过了什么,他们为什么要把这个漂亮的映射存在于一个 Action 中,但不提供一种方法来手动反向工作以创建 URL?

最佳答案

我也遇到了这个问题并使用了 Zack 的代码,但在其中发现了一个错误。如果 IEnumerable 是一个字符串数组 (string[]),那么就有问题了。所以我想我会分享我的扩展版本。

    public static RouteValueDictionary ToRouteValueDictionaryWithCollection(this RouteValueDictionary routeValues)
{
var newRouteValues = new RouteValueDictionary();

foreach(var key in routeValues.Keys)
{
object value = routeValues[key];

if(value is IEnumerable && !(value is string))
{
int index = 0;
foreach(object val in (IEnumerable)value)
{
if(val is string || val.GetType().IsPrimitive)
{
newRouteValues.Add(String.Format("{0}[{1}]", key, index), val);
}
else
{
var properties = val.GetType().GetProperties();
foreach(var propInfo in properties)
{
newRouteValues.Add(
String.Format("{0}[{1}].{2}", key, index, propInfo.Name),
propInfo.GetValue(val));
}
}
index++;
}
}
else
{
newRouteValues.Add(key, value);
}
}

return newRouteValues;
}

关于asp.net-mvc - 将复杂类型的数组添加到 RouteValueDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960420/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com