MVC3 (ASP.NET) 中何时创建模型对象

发布于 2024-11-07 10:47:28 字数 435 浏览 0 评论 0原文

尝试了解模型对象何时在 MVC3 中实例化:

我有一个用于编辑“Person”的视图;每个人可以有多个地址。我在人员视图上的网格中显示地址。

这在展示人物时效果很好;我有一个部分视图,它迭代 Person.Addresses 并构建表/网格。

创建新人员时会出现问题:人员对象为 null 并且 Person.Addresses 引用非法。

我确信我在这里遗漏了一些相当基本的东西:因为 MVC 将(自动神奇地)在“保存”时创建新的人员实例;尝试创建自己的对象实例似乎是适得其反的,如果我这样做,则不清楚如何将其连接到表单上的其余条目值。

最后一个复杂之处:地址列表是可选的;没有地址是完全合法的。

由于关系数据如此常见,因此必须有一个更简单的解决方案来处理这个问题。感谢所有澄清!

Trying to understand when model objects are instantiated in MVC3:

I have a view for editing a "Person"; each person can have multiple addresses. I'm displaying the addresses in a grid on the Person View.

This works great when displaying a person; I have a partial view which iterates through Person.Addresses and builds the table/grid.

The problem arises when creating a new person: the person object is null and the Person.Addresses reference is illegal.

I'm certain I'm missing something fairly fundamental here: since MVC will be (auto-magically) creating the new person instance upon "Save"; it would seem counter-production to try and create my own object instance, and if I did, it is unclear how I would connect it to the rest of the entry values on the form.

One last complications: the list of Addresses is optional; it is perfectly legal not to have an address at all.

As relational data is so common, there has to be a simpler solution for handling this. All clarifications appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

べ繥欢鉨o。 2024-11-14 10:47:29

这个问题的答案是对象是根据表单中的 POST 数据重新构成的。这是相当基本的,但是 MVC 隐藏了太多正在发生的事情,以至于当您试图了解 (MVC) 方向时很难看到。

项目的顺序是:

  1. 创建包含所有必需字段的表单;对不显示的键 (ID) 使用隐藏字段。
  2. 用户与网页交互;然后按表单提交按钮。
  3. 所有字段数据都会发布到控制器页面。
  4. MVC 将数据重新构成类对象。
  5. 使用重构的类实例作为形式参数来调用控制器页面。

注意:

创建页面时:会生成一个表单,其中包含所表示对象的每个部分的字段。 MVC 使用 ID 和其他非显示数据以及验证规则的隐藏字段。
值得注意的是,表单(通常)通过在 _CreateOrEdit.cshtml 页面上列出所有对象属性来创建:

// Edit.cshtml
@model Person

@Html.Partial("_CreateOrEdit", Model)

或者

// _CreateOrEdit.cshtml
@model Person

@Html.HiddenFor(model => model.PersonID)

@Html.LabelFor(model => model.first_name, "First Name")
@Html.EditorFor(model => model.first_name)

@Html.LabelFor(model => model.last_name, "Last Name")
@Html.EditorFor(model => model.last_name)

@Html.LabelFor(model => model.favorite_color, "Favorite Color")
@Html.EditorFor(model => model.favorite_color)

//etcetera

通过使用类模板(模板必须与类具有相同的名称)它们代表并位于 Views\Shared\EditorTemplates 文件夹中)。

使用模板页面与之前的方法几乎相同:

// Edit.cshtml
@model Person

@Html.EditorForModel()

并且

// Shared\EditorTemplates\Person.cshtml
@model Person

@Html.HiddenFor(model => model.PersonID)

@Html.LabelFor(model => model.first_name, "First Name")
@Html.EditorFor(model => model.first_name)

@Html.LabelFor(model => model.last_name, "Last Name")
@Html.EditorFor(model => model.last_name)

@Html.LabelFor(model => model.favorite_color, "Favorite Color")
@Html.EditorFor(model => model.favorite_color)

//etcetera

使用模板方法可以轻松地将(对象)列表添加到表单中。 Person.cshtml 变为:

// Shared\EditorTemplates\Person.cshtml
@model Person

@Html.HiddenFor(model => model.PersonID)

@Html.LabelFor(model => model.first_name, "First Name")
@Html.EditorFor(model => model.first_name)

@Html.LabelFor(model => model.last_name, "Last Name")
@Html.EditorFor(model => model.last_name)

@Html.LabelFor(model => model.favorite_color, "Favorite Color")
@Html.EditorFor(model => model.favorite_color)

@EditorFor( model => model.Addresses )

//etcetera

并且

// Shared\EditorTemplates\Address.cshtml
@model Address
@Html.HiddenFor(model => model.AddressID)

@Html.LabelFor(model => model.street, "Street")
@Html.EditorFor(model => model.street)

@Html.LabelFor(model => model.city, "City")
@Html.EditorFor(model => model.city)

//etcetera

MVC 将根据需要为列表中的每个地址创建尽可能多的表单条目。

POST 的工作原理正好相反;创建模型对象的新实例,调用默认的无参数构造函数,然后 MVC 填充每个字段。通过反转 @Html.EditorFor( model.List ) 的序列化过程来填充列表。需要注意的是,您必须确保您的类在构造函数中为列表创建了一个有效的容器,否则 MVC 的列表重新构建将失败:

public class Person
{
    public List<Address> Addresses;

    public Person()
    {
        // You always need to create this List object
        Addresses = new List<Address>();
    }

    ...
}

就是这样。幕后发生了很多事情,但都是可以追踪的。

如果您遇到此问题,请注意以下两点:

  1. 确保您拥有 @Html.HiddenFor(...) 来处理返回服务器的过程中需要“幸存”的所有内容。
  2. 使用 Fiddler 或 HTTPLiveHeaders(Firefox 插件)检查 POST 数据的内容。这将让您验证发送回的数据以重新构成新的类实例。我偏爱 Fiddler,因为您可以在任何浏览器中使用它(并且它显示表单数据的效果特别好)。

最后一点:有一篇关于使用 MVC 动态添加/删除列表中的元素的好文章: http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3 这是一篇很好的文章,值得研究——是的,它确实可以与 MVC3 和 Razor 配合使用。

The answer to this question is that the objects are re-constituted from the POST data in the form. This is fairly basic, but MVC hides so much of what is happening that it is hard to see when you are trying to get your (MVC) bearings.

The sequence of items is:

  1. Create form with all necessary fields; use hidden fields for non-displayed keys (ID).
  2. User interacts with web page; then presses form submit button.
  3. All field data is POSTed to the controller page.
  4. MVC re-constitutes the data into class objects.
  5. The controller page is invoked with the re-constituted class instance as a formal parameter.

Notes:

When creating the page: a form is generated with fields for each part of the object being represented. MVC uses hidden fields for ID's and other non-displayed data as well as for validation rules.
It is worth noting that forms are created (typically) either by listing all object properties on the _CreateOrEdit.cshtml page:

// Edit.cshtml
@model Person

@Html.Partial("_CreateOrEdit", Model)

and

// _CreateOrEdit.cshtml
@model Person

@Html.HiddenFor(model => model.PersonID)

@Html.LabelFor(model => model.first_name, "First Name")
@Html.EditorFor(model => model.first_name)

@Html.LabelFor(model => model.last_name, "Last Name")
@Html.EditorFor(model => model.last_name)

@Html.LabelFor(model => model.favorite_color, "Favorite Color")
@Html.EditorFor(model => model.favorite_color)

//etcetera

or by using a template for the class (templates must have the same name as the class they represent and they are located in the Views\Shared\EditorTemplates folder).

Using template pages is almost identical to the previous method:

// Edit.cshtml
@model Person

@Html.EditorForModel()

and

// Shared\EditorTemplates\Person.cshtml
@model Person

@Html.HiddenFor(model => model.PersonID)

@Html.LabelFor(model => model.first_name, "First Name")
@Html.EditorFor(model => model.first_name)

@Html.LabelFor(model => model.last_name, "Last Name")
@Html.EditorFor(model => model.last_name)

@Html.LabelFor(model => model.favorite_color, "Favorite Color")
@Html.EditorFor(model => model.favorite_color)

//etcetera

Using the template method makes it easy to add lists (of object) to the form. Person.cshtml becomes:

// Shared\EditorTemplates\Person.cshtml
@model Person

@Html.HiddenFor(model => model.PersonID)

@Html.LabelFor(model => model.first_name, "First Name")
@Html.EditorFor(model => model.first_name)

@Html.LabelFor(model => model.last_name, "Last Name")
@Html.EditorFor(model => model.last_name)

@Html.LabelFor(model => model.favorite_color, "Favorite Color")
@Html.EditorFor(model => model.favorite_color)

@EditorFor( model => model.Addresses )

//etcetera

and

// Shared\EditorTemplates\Address.cshtml
@model Address
@Html.HiddenFor(model => model.AddressID)

@Html.LabelFor(model => model.street, "Street")
@Html.EditorFor(model => model.street)

@Html.LabelFor(model => model.city, "City")
@Html.EditorFor(model => model.city)

//etcetera

MVC will handle creating as many form entries as necessary for each address in the list.

The POST works exactly in reverse; a new instance of the model object is created, calling the default parameter-less constructor, and then MVC fills in each of the fields. Lists are populating by reversing the serialization process of @Html.EditorFor( model.List ). It is important to note that you must make certain your class creates a valid container for the list in the constructor otherwise MVC's list re-constitution will fail:

public class Person
{
    public List<Address> Addresses;

    public Person()
    {
        // You always need to create this List object
        Addresses = new List<Address>();
    }

    ...
}

That cover's it. There is a lot going on behind the scenes, but it is all track-able.

Two important points if you are having trouble with this:

  1. Make sure you have @Html.HiddenFor(...) for everything that needs to "survive" the trip back to the server.
  2. Use Fiddler or HTTPLiveHeaders (Firefox plug-in) to examine the contents of the POST data. This will let you validate what data is being sent back to re-constitute the new class instance. I'm partial to Fiddler since you can use it with any browser (and it shows form data particularly well).

One last point: there is a good article on dynamically adding / removing elements from a list with MVC: http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3 It's a good article to work through -- and yes, it does work with MVC3 and Razor.

望喜 2024-11-14 10:47:29

我假设的地址位于表中,而不是实际的输入元素,可能只是 info?
如果是这样,那么它们将不会被实例化,因为没有数据被发送回服务器。
您必须使用回发的元素创建此数据,以便将它们(按名称)映射到其属性。如果模型绑定器可以找到适当命名的发布表单(或查询字符串)元素,则模型绑定器将实例化对象并在回发时将它们传递给控制器​​。

The addresses I'm assuming are in a table, not actual input elements and likely just <td>info</td>?
If so, then they won't get instantiated as there is no data being posted back to the server.
You must have this data being created with elements that are posted back in order to have them mapped (by name) to their properties. The model binder will instantiate the objects and pass them to your controller upon postback if it can find appropriately named posted form (or querystring) elements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文