2011-02-22 36 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 
    } 
});