将list ,对象和基元的混合传递给ASP MVC控制器操作的方法
我是C#的新手,我正在创建我的第一个MVC项目,并且很难找到将不同类型的3个参数传递给控制器动作的方法。 这是我的控制器方法:
public ActionResult Create(Notification notification, string hash, list 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’)属于通知对象。 但现在我想添加一个列表 of int。
这是可以做的事情,你将如何格式化传递的数据/查询字符串?
这是可以做到的事情
是。
以及如何格式化传递的数据/查询字符串?
像这样:
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
您也可以在以下博客文章中找到有用的阅读材料。
但在将控制器操作签名转换为一些spaghettified代码和代码读者之前,必须水平循环几个屏幕以查看此操作所需的数百万个参数,停止疯狂并引入视图模型:
public class CreateViewModel { public Notification Notification { get; set; } public string Hash { get; set; } public List 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