子记录未发布在ASP.NET MVC表单上 [英] Child records not posting on ASP.NET MVC form

查看:52
本文介绍了子记录未发布在ASP.NET MVC表单上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,作者和书,其中一个作者可以有很多书.我已经将编辑视图设置为"System.Web.Mvc.ViewPage(属于MyDatabase.Author)".设置表单以显示作者及其所有书籍,并能够编辑书籍信息:

I have two tables, Author and Book, where an author can have many books. I've got an edit view set up as "System.Web.Mvc.ViewPage(of MyDatabase.Author)". The form is set up to show the Author and all his books, with the ability to edit book information:

<% Using Html.BeginForm()%>
<%=Model.author_name%> <br/>
<% For Each item In Model.Books%>
<%=Html.CheckBox("checked_out")%>
<%=item.book_name%> <br/>
<% Next%>
<input type="submit" value="Save" />
<% End Using%>

在控制器中,我具有Post函数:

In the controller, I've got the Post function:

<ActionName("Edit"), AcceptVerbs(HttpVerbs.Post)> _
Function Save(ByVal form As Author) As ActionResult
   Dim book_count = Author.Books.Count
End Function

问题在于,即使显示了几本图书,Books集合也不是该帖子的一部分-book_count为零.

The problem is that the Books collection isn't part of the post - book_count is zero, even though there are several books displayed.

我是在做错什么,还是在帖子中期望太多?我该如何进行这项工作?

Am I doing something wrong, or am I expecting too much in the post? How can I make this work?

推荐答案

我相信您的问题是MVC的魔术解析器"没有什么可负担的.当您希望在页面上放置要在集合中枚举的帖子的项目时,必须给您的事物"命名.因此,我在页面中所做的就是如果我不希望他们能够编辑字段,例如上面的书名,我将使用隐藏字段将值包装在MVC可以通过的控件中魔术,然后还向用户显示该值.因此,它可能类似于:

I believe your problem is that the "magic parser" for MVC has nothing to hang it's hat on. When you put items on your page that you want to be able to grab back on the post that are enumerated inside of a collection, you've got to give your "things" names. So, what I did in my page is if I didn't want them to be able to edit a field, like your book name above, I would use a hidden field to wrap the value up in a control that MVC can get at via magic and then also display that value to the user. So, it could look something like:

<% for (i = 0; i < Model.Books.Count; i++) {
       book = Model.Books[i] as book //I'm a C# guy so make this VB
<%= Html.CheckBox("author["+1+"].checked_out", book.checked_out) %>
<%= HtmlHidden("author["+i+"].book_name",book.book_name) %>
<%= book.book_name %>
<% } %>

...然后这应该会回来,所有内容都很好地打包为您作为Authors对象中的书集.看看是否能正确引导您.

...and then this should come back all nicely packaged for you as a book collection in your Authors object. See if that gets you in the right direction.

编辑另一个想法也一样.我正在使用UpdateModel方法来获取结果.没关系,但我想我会把它扔在那里.

EDIT One other thought too. I'm using the UpdateModel method to fetch the results. It shouldn't matter, but I thought I'd throw that in there.

这篇关于子记录未发布在ASP.NET MVC表单上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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