2011-08-30 19 views
1

有没有一种方法来构建表单的html以发布Item类的所有数据?这里是类和控制器动作:AJAX在MVC中的表单结构中发布对象

public class Item 
{ 
    public Item(){} 

    public string Name { get; set; } 
    public string Description { get; set; } 
    public List<string> Tag { get; set; } 
    public List<Note> Notes {get; set; } 
} 

public class Note 
{ 
    public string Id { get; set; } 
    public string NoteText { get; set; } 
    public string OtherStuff { get; set; } 
} 

[HttpPost] 
public ActionResult SaveItemcontroller(Item SubmittedItem) 
{ 
    DataLayer.Save(SubmittedItem); 
} 

当我张贴下面我的动作方法获得与名称,描述的对象,标签列表:

$.ajax({ type: "POST", dataType: "json", url: $(form).attr('action'), data: $(form).serialize()}); 

<form method="post" action="/saveitemcontroller"> 
    <input id="Name" name="Name" type="text"> 
    <input id="Description" name="Description" type="text"> 
    <input name="Tag" type="text"> 
    <input name="Tag" type="text"> 
    <input name="Tag" type="text"> 
    <input name="Tag" type="text"> 
</form> 

我的问题,是有没有如何构造html以包含POSTed Item对象内的Note对象?或者是在JavaScript数据对象被序列化后玩弄的唯一方法?

SOLUTION

<input name="Notes[0].Id" type="text"> 
    <input name="Notes[0].NoteText" type="text"> 
    <input name="Notes[0].OtherStuff" type="text"> 


    <input name="Notes[1].Id" type="text"> 
    <input name="Notes[1].NoteText" type="text"> 
    <input name="Notes[1].OtherStuff" type="text"> 


    <input name="Notes[2].Id" type="text"> 
    <input name="Notes[2].NoteText" type="text"> 
    <input name="Notes[2].OtherStuff" type="text"> 


</form> 

注:当使用JavaScript来添加或删除新的集团,它需要确保该序列在零和增加+1开始没有跳过任何数字。以保持指数的数值序列的轨道另一种方法是创建一个链接的每个组合在一起,一个隐藏的索引元素:

<input name="Notes[**anythingstring**].Id" type="text"> 
    <input name="Notes[**anythingstring**].NoteText" type="text"> 
    <input name="Notes[**anythingstring**].OtherStuff" type="text"> 
    <input name="Notes.Index" type="hidden" value="**anythingstring**"> 

回答

1

如果使用

Html.EditorFor(o=>o.Notes) 

这些项目我认为应该用正确的渲染对他们的IDS说明,只要您只是序列化表单,模型联编程序就会正确选取。

+0

感谢您的指导。你的帖子引导我到这个:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx – Parmenides

+0

你可以专门发布什么为你工作让别人看?谢谢! –