从视图模型列表更新模型

时间:2012-11-30 10:13:32

标签: asp.net-mvc-3 model-binding

View是这样的(我动态添加和删除文档,这里编写的Guids是ViewModel的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>

我有这样的viewmodel:

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 个答案:

答案 0 :(得分: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;
}

希望这可以提供帮助。