![](/img/trans.png)
[英]How to dynamically add to list with ViewModel in ASP.NET Core 3.1 MVC with JavaScript and C#
[英]ASP.Net MVC ViewModel contains List<anotherViewModel> dynamically add list entry for anotherViewModel
我找不到並解決如何通過加載在編輯視圖中的另一個ViewModel來動態添加ViewModel條目。
可以說我有一個ViewModel,它包含另一個ViewModel的列表。
數據庫模型:
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; }
}
用戶加載包含ViewModel的編輯視圖,該視圖當前具有2個類型為anotherViewModel的條目。
用戶應該可以將另一個類型anotherViewModel的條目添加到ViewModel中,甚至可以更改anotherViewModel條目的屬性。
另一個ViewModel在局部視圖中。 我試圖用ajax重新加載它,如果這樣做,當前模型中所做的更改將丟失。 因為我無法交出控制器模型。
我知道jquery必須有一些解決方案,但是我找不到。
謝謝你的幫助。
傳統方式(用偽代碼):在您的視圖中,您將創建以下內容:
<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列表,在部分視圖中,您將具有anotherViewModel的html標記。 當用戶編輯了現有視圖和/或添加了新元素后,“提交”按鈕將把整個viewmodel和anotherViewModels列表發布到您的操作中。 然后,該操作將處理添加和更新。
但是,這確實僅適用於並發異常幾率低的應用程序。 一種更平滑的方法是讓每個局部視圖對其包含的數據負責,並通過ajax對其進行持久化。 這樣就無需一次性發布所有更改。
您的視圖模型將在剃須刀助手的幫助下轉換為html元素。 當用戶在客戶端上編輯viewmodels數據時,您實際上是在編輯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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.