用于将列表,对象和基元的混合传递给ASP MVC控制器操作的方法 [英] Methodology for passing a mix of: list<>, object and primitives to an ASP MVC controller action
问题描述
我刚接触C#,正在创建我的第一个MVC项目,并且很难弄清楚将3个不同类型的参数传递给控制器动作的方法.这是我的控制器方法:
I'm fairly new to C#, and am creating my first MVC project, and am having a hard time figuring out the methodology of passing 3 parameters of varying types to a controller action. Here is my controller method:
public ActionResult Create(Notification notification, string hash, list<int> users){
//code inside method irrelevant...
}
和我的通知模型:
public class Notification
{
public int ID { get; set; }
public string ApplicationID { get; set; }
public string Description { get; set; }
public System.DateTime DateStamp { get; set; }
}
在添加List<>参数之前,它可以通过像这样发布数据(或查询字符串)来正常工作:
Before I added the List<> parameter it worked fine by having the posted data (or querystring) like so:
ApplicationID=1&Description=yo&hash=abcdefg
它神奇地知道这两个参数("ApplicationID"和"Description")属于通知对象.但是现在我想添加一个int列表.
And it magically knew that the two parameters ('ApplicationID' and 'Description') belonged to the notification object. But now I'd like to add in a list<> of ints.
这是可以完成的事情吗,您将如何格式化传递的数据/查询字符串?
Is this something that can be done and how would you format the data/querystring passed?
推荐答案
这是可以做的事情
Is this something that can be done
是的
以及如何格式化传递的数据/查询字符串?
and how would you format the data/querystring passed?
赞:
ApplicationID=1&Description=yo&hash=abcdefg&users=1&users=2&users=3
或者如果您喜欢这样:
ApplicationID=1&Description=yo&hash=abcdefg&users[0]=1&users[1]=2&users[2]=3
Also you might find the following blog post an useful read.
但是在将控制器动作签名转换为一些杂乱无章的代码之前,您的代码阅读者必须水平移动几个屏幕才能看到该动作所需要的数百万个参数,阻止这种疯狂行为并引入一个视图模型:>
But before transforming your controller action signatures into some spaghettified code and readers of your code having to cycle a couple of screens horizontally in order to see the millions of parameters this action takes, stop the madness and introduce a view model:
public class CreateViewModel
{
public Notification Notification { get; set; }
public string Hash { get; set; }
public List<int> Users { get; set; }
}
然后:
public ActionResult Create(CreateViewModel model)
{
//code inside method irrelevant...
}
然后:
notification.applicationID=1¬ification.description=yo&hash=abcdefg&users[0]=1&users[1]=2&users[2]=3
这篇关于用于将列表,对象和基元的混合传递给ASP MVC控制器操作的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!