ASP.NET MVC - 将数组对象作为 Html.ActionLink(...) 中的路由值传递 [英] ASP.NET MVC - Pass array object as a route value within Html.ActionLink(...)

查看:16
本文介绍了ASP.NET MVC - 将数组对象作为 Html.ActionLink(...) 中的路由值传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数组 (string[]) 的方法,我正在尝试将这个字符串数组传递给 Action Link,以便它创建一个类似于以下内容的查询字符串:

I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action Link so that it will create a query string similar to:

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

但是当我通过 new { str = GetStringArray() } 我得到以下网址:

But when I pass new { str = GetStringArray() } I get the following url:

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

所以基本上它使用我的 string[] 并在其上运行 .ToString() 来获取值.

So basically it's taking my string[] and running .ToString() on it to get the value.

有什么想法吗?谢谢!

推荐答案

尝试创建一个包含您的值的 RouteValueDictionary.您必须为每个条目指定一个不同的键.

Try creating a RouteValueDictionary holding your values. You'll have to give each entry a different key.

<%  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 ) %>

会给你一个类似的链接

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

编辑:MVC2 更改了 ValueProvider 接口,使我原来的答案过时了.您应该使用具有字符串数组作为属性的模型.

EDIT: MVC2 changed the ValueProvider interface to make my original answer obsolete. You should use a model with an array of strings as a property.

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

然后模型绑定器将使用您在 URL 中传递的值填充您的模型.

Then the model binder will populate your model with the values that you pass in the URL.

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

这篇关于ASP.NET MVC - 将数组对象作为 Html.ActionLink(...) 中的路由值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆