2012-11-30 194 views
1

觀是這樣的(我動態添加和刪除文件,這裏寫的GUID視圖模型的DocumentIdentifier成員):更新模型

<div> 
    <input type="hidden" name="DocumentViewModels.Index" value="8796c4e8-2262-46c0-bacc-8ffb6678b62a" /> 
    <input type="text" name="DocumentViewModels[8796c4e8-2262-46c0-bacc-8ffb6678b62a].Document.Name" /> 
    <input type="text" name="DocumentViewModels[8796c4e8-2262-46c0-bacc-8ffb6678b62a].Document.Type" /> 
<div> 

<div> 
    <input type="hidden" name="DocumentViewModels.Index" value="3f2810c6-e338-4a6a-aa64-54b162303aab" /> 
    <input type="text" name="DocumentViewModels[3f2810c6-e338-4a6a-aa64-54b162303aab].Document.Name" /> 
    <input type="text" name="DocumentViewModels[3f2810c6-e338-4a6a-aa64-54b162303aab].Document.Type" /> 
<div> 

我視圖模型是這樣的:

public class DocumentViewModel 
{ 
    public Document Document {get;set;} 
    public List<Attachments> {get;set;} 
    public Guid DocumentIdentifier {get;set;} 
} 

控制器

public ActionResult PostDocuments(List<DocumentViewModel> documentViewModels) 
{ 
    // I successfully save newly added documents in database 
    // Then I delete documents from database that are not in documentViewModels any more (because I dynamically add and delete them) 
    // Then I find documents that are on form and in database too and I want to update them 
    List<Document> matchedDocumentsFromDatabase = SynchronizeDocuments(documentViewModels.Select(x => x.Document)); 
    // Here i'm stuck. I want to write something like this: 
    UpdateModel(matchedDocumentsFromDatabase, "DocumentViewModels"); 
    context.SaveChanges(); 
    // return something; 
} 

你能幫助我嗎?

回答

1

你可以使用前綴如下。

public ActionResult PostDocuments(List<DocumentViewModel> documentViewModels) 
{ 
    // I successfully save newly added documents in database 
    // Then I delete documents from database that are not in documentViewModels any more (because I dynamically add and delete them) 
    // Then I find documents that are on form and in database too and I want to update them 
    var matchedDocumentsFromDatabase = SynchronizeDocuments(documentViewModels.Select(x => x.Document)); 
    // Here i'm stuck. I want to write something like this: 
    string prefix = ""; 
    foreach(var item in matchedDocumentsFromDatabase) 
    { 
     prefix = string.Format("DocumentViewModels[{0}]",item.DocumentIdentifier .ToString()); 
     UpdateModel(item, prefix); 
    } 
    context.SaveChanges(); 
    // return something; 
} 

希望這可以幫助。

+0

View中編寫的guid不是文檔的id。請參閱更新 – karaxuna

+0

我需要guids來區分新添加的文檔(在ID的情況下,它們都將具有id = 0) – karaxuna

+0

無論如何,DocumentIdentifier都與您的視圖模型關聯。不是嗎? –