我对 C# 相当陌生,正在创建我的第一个 MVC 项目,并且很难弄清楚将 3 个不同类型的参数传递给控制器操作的方法。这是我的控制器方法:
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 参数之前,它通过发布数据(或查询字符串)来正常工作,如下所示:
ApplicationID=1&Description=yo&hash=abcdefg
它神奇地知道这两个参数(“ApplicationID”和“Description”)属于通知对象。但现在我想添加一个整数列表。
这是可以完成的事情吗?您将如何格式化传递的数据/查询字符串?
这是可以做的事情吗
Yes.
以及如何格式化传递的数据/查询字符串?
像这样:
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
您还可能会发现以下博客文章 http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx一本有用的读物。
但是,在将控制器操作签名转换为一些意大利面条化的代码之前,代码的读者必须水平循环几个屏幕才能看到该操作所采用的数百万个参数,停止疯狂并引入视图模型:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)