我正在尝试使用ASP.NET的模型绑定并使用JavaScript处理一堆值,将模型列表发布到服务器。当我将值发送到服务器时,这就是我得到的:
model.inventory.processed_items[0].id: GA-6570
model.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: 0
model.inventory.processed_items[1].id: GD-1000
model.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);
}
[HttpPost]
public ActionResult Create(PackageViewModel packageVM)
{
if (ModelState.IsValid)
{
...
}
}
当我在调试器中检查packageVM时,这些值未绑定到视图模型。但是,在POST请求期间,packageVM模型中将包含除此嵌套模型列表之外的其他值。我不明白为什么这部分没有绑定,因为我提供了索引并且还向视图中传递了一个空列表。
答案 0 :(得分:1)
您要发送的值的属性名称与您要绑定的模型不匹配。 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
因为方法中的参数名为packageVM
,所以只需删除该前缀(即变为inventory.processed_items[0].id
),这就是绑定数据的名称。 / p>
请注意,您正在***For()
循环中使用强类型的for
方法来根据模型生成表单控件,它们将生成正确的name
属性,您只需使用$('form').serialize()
即可正确生成要通过ajax调用发送的数据。