2014-03-28 28 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。