asp.net mvc 如何将集合传递给控制器
这个问题比较有趣: 当我有用于创建模板的强类型视图时,如何将集合传递给控制器。 这是我的 ViewModel:
public class AgencyOfficiesItem
{
public string Address { get; set; }
public List<PhoneItem> Phones { get; set; }
public List<SelectListItem> CitiesList { get; set; }
}
public class PhoneItem {
public string Phone { get; set; }
public string PhoneOperator { get; set; }
}
因此,我想创建一个用于创建电话对象的视图,其中包含电话运营商和电话号码字段。但是,有趣的是我想收集手机对象的集合并将它们传递给控制器。有什么想法吗?
The question rather interesting:
How can I pass collection to the controller when i have strondly-typed view for create template.
This is my ViewModel:
public class AgencyOfficiesItem
{
public string Address { get; set; }
public List<PhoneItem> Phones { get; set; }
public List<SelectListItem> CitiesList { get; set; }
}
public class PhoneItem {
public string Phone { get; set; }
public string PhoneOperator { get; set; }
}
So, I want to create a view for creating the phone object, which has the phone operator and phone number fields. But, the interesting thing is that i want to have a collection from phone objects and pass them to the controller. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您继续执行您认为的类似操作:
并按如下方式声明您的 post 方法
,那么一切都应该没问题。 MVC 将定义生成的文本框,以便能够在回发时将它们与模型链接起来。我相信它的作用是将文本框上的名称属性声明为,例如 Phones_1_Phone。您可以通过在浏览器中查看生成的 HTML 来进行检查。
顺便说一句,还有其他方法可以让它发挥作用。您可以使用带有 Dictionary<> 的键。我相信,而不是 List<> 和稀疏数组。当然,您想要做的不仅仅是在页面上生成一堆文本框 - 一些标签会很好:)。
我发现 Apress 提供的 Steven Sanderson 的 Pro ASP.NET MVC 2 Framework 是关于此方面的一个很棒的教程以及更多内容。几个月前,我开始对 MVC 一无所知,现在我对它非常满意(尽管还不是专家)。
糟糕,忘记提及一些重要的事情:我的示例使用 MVC3 及其 Razor 视图引擎。如果您不使用 MVC3,则需要将其转换为 MVC2 语法。但你应该看一下 MVC3,我发现它比它的前辈更直观。更不用说少“罗嗦”了。
If you just go ahead and do something like this in your view:
and declare your post method as follows
then all should be well. MVC will define the resulting textboxes in a way that it will be able to link them back up with the model on postback. I believe what it does is declare the name attribute on the textbox to be, for example, Phones_1_Phone. You can check by looking at the generated HTML in your browser.
BTW, there are other ways of getting this to work, too. You can use keys, with a Dictionary<> rather than a List<>, and sparse arrays, too, I believe. And of course you'll want to do something more than just generate a bunch of textboxes on your page -- some labels would be nice :).
I found that a great tutorial on this and much more is Steven Sanderson's Pro ASP.NET MVC 2 Framework, from Apress. I started off knowing nothing about MVC just a couple of months ago, and now I'm quite comfortable with it (although not yet an expert).
Oops, forgot to mention something important: my example uses MVC3 and its Razor view engine. You'll need to translate it into MVC2 syntax if you're not using MVC3. But you should give MVC3 a look, I find it more intuitive than its predecessors. Not to mention less "wordy".