2011-02-22 60 views
2

我有点麻烦如何做到这一点。帮助与多个模型的asp.net mvc形式

,这里是我的情况

一个User必须为他的Business创建IncomeDeclaration

但是IncomeDeclaration包括许多ActivityIncomeDeclarations,其中包括他的业务所在的每个Activity

我想我的形式包括新IncomeDeclaration的领域以及为ActivityIncomeDeclarations的字段(这将明显与该IncomeDeclaration)....

我知道rubyonrails有一个方法所谓“accep_nested_attributes_for”tgat可能会帮助我在这里..

请帮助!

+0

您的意思是继承吗? – Aliostad 2011-02-22 19:25:31

+0

否..许可证has_many活动...许可证has_many(IncomeDeclarations ..年度基准)..每个收入声明都会有很多活动,因为当他声明 – ignaciofuentes 2011-02-22 19:31:19

回答

1

这很容易实现。 ASP NET MVC是非常有构图的,你可以使用模板来实现这一点,但继承是不是要走的路。

这样的解决方案是IncomeDeclaration包含的ActivityIncomeDeclarations列表,然后做到这一点:

for(int i=0; i< Model.Activities.Count; i++) 
{ 
    Html.EditorFor(Model.Activities[i]); // you need an editor template (and a display template) for ActivityIncomeDeclarations 
} 

更多信息:

http://www.asp.net/mvc/videos/mvc2-template-customization http://www.dalsoft.co.uk/blog/的index.php/2010/4月26日/ MVC-2模板/

1

这个矿的博客文章可以帮助你很多:

Asp.net MVC model binding to List<T>

但基本上,您会为您的IncomeDeclaration提供字段,然后根据需要动态添加ActivityIncomeDeclaration字段。

如果你想实际序列化表单,你将不得不遵循上部博文中提供的指令。

但如果您使用jQuery,还有第二种选择。你可以操纵一个复杂的JavaScript对象,它会像在同一个服务器端的C#类的副本:

var incDec = { 
    Name: "" 
    // and other properties 
    ActivityIncomeDeclarations: [] 
}; 

然后同时用户将被添加这些ActivityIncomeDeclarations你永远只需拨打

incDec.ActivityIncomeDeclarations.push({ 
    // properties 
}); 

然后我的其他博客文章将帮助您可在此对象转换为一个字典,jQuery的例如是轻易就能过程:

Sending complex JSON objects to Asp.net MVC using jQuery

通过使用prlogin博客文章,您可以轻松做到:

$.ajax({ 
    url: "someURL", 
    type: "POST", 
    data: $.toDictionary(incDec), 
    success: function(data, status, xhr){ 
     // process success 
    }, 
    error: function(xhr, status, err){ 
     // process error 
    } 
});