将对象列表从视图传递到ASP.NET MVC中的控制器? [英] Passing a list of object from a view to the controller in asp.net mvc?

查看:75
本文介绍了将对象列表从视图传递到ASP.NET MVC中的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?
我想做的是在操作链接中将对象列表作为参数传递
在我尝试执行此操作时,列表到达控制器时始终为空!

Is this possible?
What I want to do is pass a list of objects as a paramter in an actionlink
At the moment when I try to do this the list is always empty by the time it reaches the controller!

在视图中

 <%= Url.Action("ActionName", new { list = Model.ListOfObjects}) %>

在控制器中

public ActionResult ActionName(List<Object> list)
    {
        //Do stuff
    }

推荐答案

关于是否可能-可能,但不是您尝试的方式.请记住,这将转换为将由MVC解析的URL,并且不同的参数将作为直接参数或通过模型绑定器传递给操作.

In terms of whether or not it's possible - it's possible, but not in the way you're trying. Keep in mind that this will translate to a URL which will get parsed by MVC and the different parameters will get passed to the action either as direct parameters or through a model binder.

我建议您尝试确定URL的外观,然后执行一些自定义代码来生成URL(可能使用自定义辅助函数/扩展方法).如果将其与自定义模型活页夹结合使用,则应该有一个非常优雅的解决方案,该解决方案可以完全满足您的需求.

I would recommend that you try to figure out what the URL will have to look like and then maybe do some custom code to generate the URL (maybe use a custom helper function/extension method). If you combine this with a custom model binder you should have a pretty elegant solution which does exactly what you want.

例如,如果您的列表中有3个类型为string的对象,则可以编写一个帮助程序来生成这样的url(假设列表包含"first","second"和"third")

For example, if your list has 3 objects of type string you could write a helper to generate a url like this (let's say the list contains 'first', 'second', and 'third')

/Controller/Action?obj1 = first& obj2 = second& obj3 = third

/Controller/Action?obj1=first&obj2=second&obj3=third

现在,您只需要编写一个模型绑定程序,即可查找名为"obj1","obj2"等的条目,并将结果添加到列表中即可.

Now you simply need to write a model binder that looks for entries called 'obj1','obj2', etc and simply add the results into a list.

这篇关于将对象列表从视图传递到ASP.NET MVC中的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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