我正在嘗試將模型列表發布到服務器,使用 ASP.NET 的模型綁定并使用 JavaScript 操作一堆值。當我將值發送到服務器時,這就是我得到的:model.inventory.processed_items[0].id: GA-6570model.inventory.processed_items[0].event: model.inventory.processed_items[0].subevent: model.inventory.processed_items[0].restrict_marking: model.inventory.processed_items[0].cecp_string: model.inventory.processed_items[0].discrepancies: model.inventory.processed_items.Index: 0model.inventory.processed_items[1].id: GD-1000model.inventory.processed_items[1].event: model.inventory.processed_items[1].subevent: model.inventory.processed_items[1].restrict_marking: model.inventory.processed_items[1].cecp_string: model.inventory.processed_items[1].discrepancies: model.inventory.processed_items.Index: 1這些是我要綁定到的模型類(我省略了與問題無關的任何字段):public class PackageViewModel{ public InventoryViewModel inventory { get; set; }}public class InventoryViewModel{ public List<ProcessedItemViewModel> processed_items { get; set; }}public class ProcessedItemViewModel{ public string id { get; set; } public int @event { get; set; } public string subevent { get; set; } public string cecp_string { get; set; } public string restrict_marking { get; set; } public string discrepancies { get; set; } public string highest_classification { get; set; } public int occurences_count { get; set; } public IEnumerable<ProcessedOccurenceViewModel> occurences { get; set; }}public class ProcessedOccurenceViewModel{ public string text { get; set; } public string security_num { get; set; } public Nullable<int> media_count { get; set; } public string classification { get; set; }}這是我的控制器:[HttpGet]public ActionResult Create(){ var inventoryVM = new InventoryViewModel { processed_items = new List<ProcessedItemViewModel>() }; var packageVM = new PackageViewModel { inventory = inventoryVM }; return View(packageVM);}當我在調試器中檢查 packageVM 時,這些值未綁定到視圖模型。但是,在 POST 請求期間,除此嵌套模型列表之外的其他值包含在 packageVM 模型中。我不明白為什么這部分沒有約束力,因為我提供了索引并且還向視圖傳遞了一個空列表。
1 回答

一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
您發送的值的屬性名稱與您綁定到的模型不匹配。PackageViewModel不包含名為的屬性model(它包含一個名為inventory),因此而不是
model.inventory.processed_items[0].id: GA-6570
它需要是
inventory.processed_items[0].id: GA-6570
考慮這個問題的一個簡單方法是考慮如何在 POST 方法中訪問模型的屬性值
public ActionResult Create(PackageViewModel packageVM)
{
// get the id of the first item in processed_items
string id = packageVM.inventory.processed_items[0].id
因為方法中的參數是 named packageVM,只需刪除該前綴,(即變成inventory.processed_items[0].id),這就是數據的名稱,以便綁定。
作為旁注,如果您***For()在for循環中使用強類型方法來根據您的模型生成表單控件,它們將生成正確的name屬性,您可以使用它$('form').serialize()來正確生成要通過 ajax 調用發送的數據.
- 1 回答
- 0 關注
- 205 瀏覽
添加回答
舉報
0/150
提交
取消