ASP.Net MVC - 模型集合不填充在回发 [英] ASP.Net MVC - model with collection not populating on postback

查看:72
本文介绍了ASP.Net MVC - 模型集合不填充在回发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它是深含集合几层一个ASP.Net MVC应用程序。

I have an ASP.Net MVC application with a model which is several layers deep containing a collection.

我认为,要创建对象的视图所有设置正确,但它只是没有在模型中填充集合时,我发帖的形式向服务器。

I believe that the view to create the objects is all set up correctly, but it just does not populate the collection within the model when I post the form to the server.

我有一个数据是在类层次结构中发现这样的:

I have a piece of data which is found in the class hierarchy thus:

person.PersonDetails.ContactInformation[0].Data;

本类结构由LinqToSQL创建,ContactInformation类型为的EntitySet<&联络资料GT; 。要创建我通过查看以下内容:

This class structure is created by LinqToSQL, and ContactInformation is of type EntitySet<ContactData>. To create the view I pass the following:

return View(person);

和在视图中我有一​​个包含关联到上述领域的一个名字一个文本框形式:

and within the view I have a form which contains a single text box with a name associated to the above mentioned field:

<%= Html.TextBox("person.PersonDetails.ContactInformation[0].Data")%>

我的控制器中的POST方法则如下:

The post method within my controller is then as follows:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create (Person person)
{
  //Do stuff to validate and add to the database 
}

正是在这一点上,我担心迷路person.PersonDetails.ContactInformation.Count()== 0。所以ModelBinder的创造了ContactInformation对象,但没有与它应该在索引0保持(即联络资料)对象填充它。

It is at this point where I get lost as person.PersonDetails.ContactInformation.Count() ==0. So the ModelBinder has created a ContactInformation object but not populated it with the object which it should hold (i.e ContactData) at index 0.

我的问题是双重的:
1.我是否采取了正确的方法..即应这项工作?
2.任何想法,为什么它可能未填充ContactInformation对象?

My question is two fold: 1. Have I taken the correct approach.. i.e. should this work? 2. Any ideas as to why it might be failing to populate the ContactInformation object?

非常感谢,
理查德

Many thanks, Richard

推荐答案

我认为你的模型过于复杂,默认的模型绑定一起工作。你可以尝试使用多个参数和prefixes结合他们:

I think that your model is too complex for the default model binder to work with. You could try using multiple parameters and binding them with prefixes:

public ActionResult Create( 
    Person person,
    [Bind(Prefix="Person.PersonDetails")]
    PersonDetails details,
    [Bind(Prefix="Person.PersonDetails.ContactInformation")] 
    ContactInformation[] info )
{
      person.PersonDetails = details;
      person.PersonDetails.ContactInformation = info;

      ...
}

或者你也可以开发自己的定制模型绑定,将了解如何从表单输入派生复杂的模型。

Or you could develop your own custom model binder that would understand how to derive your complex model from the form inputs.

这篇关于ASP.Net MVC - 模型集合不填充在回发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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