2014-03-28 27 views
0

列表条目我不能找到和解决方案如何动态地添加通过另一个视图模型一个ViewModel进入编辑视图多数民众赞成加载。ASP.Net MVC视图模型包含的List <anotherViewModel>动态添加了anotherViewModel

可以说我有一个ViewModel这就是包含anotherViewModel的名单。

数据库模型:

public class ViewModel 
{ 
    public ViewModel() 
    { 
     anotherViewModel= new List<anotherViewModel>(); 
    } 

public string idViewModel{ get; set; } 
public string description{ get; set; } 
public List<anotherViewModel> aViewModel { get; set; } 
} 

用户加载编辑视图含有视图模型,当前具有2个entrys型anotherViewModel的。

用户应该从anotherViewModel entrys添加到视图模型类型anotherViewModel的另一个入口,甚至更改其属性的可能性。

另一个ViewModel处于局部视图。我尝试用ajax重新加载它,如果我这样做,在当前模型中所做的更改将丢失。因为我无法将模型交给控制器。

我知道必须有一些解决方案与jQuery,但我无法找到一个。

感谢您的帮助。

回答

0

传统的方式(在伪代码): 在你看来,你想创造的东西,如:

<form> 
Your html code for ViewModel properties. 
create list of partials: 
@foreach(anotherModel in Model.aViewModel) 
{ 
    @Html.Partial("_yourPartialView", anotherViewModel) 
} 
Code for adding a new anotherView element. 
ie: @Html.Partial("_createNewElement", new anotherViewModel) 
<submit button> 
</form> 

你的页面会列出anotherViewModel名单,并在局部视图您对HTML标记anotherViewModel。当用户编辑现有的元素和/或添加一个新的元素时,submit按钮会将整个视图模型与anotherViewModel的列表一起发布到您的操作中。该行动将处理添加和更新。

然而,这并往往只工作在那里的并发异常的几率是很低的应用。更平滑的做法是让每个局部视图对其包含的数据负责并通过ajax持久保存。这将无需一次性发布所有更改。

0

您的viewmodel将在剃刀助手的帮助下被转换为html元素。当用户在客户端上编辑视图模型数据时,您实际上会编辑html。当您回发给控制器时,mvc中的默认模型绑定器将尝试将您的发布数据转换为控制器操作期望的模型作为参数。当你有复杂的模型时,它会变得有点棘手。你有没有试图建立一个自定义模型联编程序?

public class CustomBinder : IModelBinder 
{ 
public object BindModel(ControllerContext controllerContext, 
         ModelBindingContext bindingContext) 
{ 
    HttpRequestBase request = controllerContext.HttpContext.Request; 

    string idViewModel= request.Form.Get("idViewModel"); 
    string description= request.Form.Get("description"); 
    var list = new List<anotherViewModel>(); //create list from form data 


    return new ViewModel 
       { 
        idViewModel= idViewModel, 
        description= description, 
        aViewModel = list 
       }; 
} 

}

,并在你的控制器动作:

public ActionResult Edit([ModelBinder(typeof(CustomBinder))] ViewModel vm) 

否则,也许你应该重新考虑你的数据结构。也许有一个单独的部分视图,您可以在其中编辑anotherViewModel。