我有一个 ViewModel,我试图将其传递给包含字典的 Controller 。我能够让所有内容在 View 中正确显示,但是当我发布到我的 Controller 时,我永远不会通过 StudentKeys 字典,但是所有其他信息都很好。
查看
@using (Html.BeginForm("BulkEditStudentRecordsAdultEd", "Order", FormMethod.Post, new { @id = "EditStudentAdultEd", @class = "form-horizontal" }))
{
@Html.HiddenFor(m => m.AdultEdAgencyCd)
foreach (var item in Model.StudentKeys)
{
@Html.HiddenFor(m => item.Key)
@Html.HiddenFor(m => item.Value)
}
<h1>@Model.StudentKeys.Count</h1>
<div class="row inputRow">
@Html.BootstrapDropDownListFor(m => m.DistrictCd, Model.DistrictCodes, "col-md-5", labelText: "District:", htmlAttributes: new { @id = "DistrictCd" })
@Html.BootstrapDropDownListFor(m => m.SchoolCd, Model.SchoolCodes, "col-md-5", labelText: "School:", htmlAttributes: new { @id = "SchoolCd" })
</div>
<div class="col-md-offset-2">
<button id="SaveStudentBulkEdit" type="submit" class="btn btn-primary btn-sm">Save <span class="badge">0</span></button>
<button id="CancelStudentBulkEdit" type="button" class="btn btn-default btn-sm" data-dismiss="modal">Cancel</button>
</div>
}
Controller
[HttpPost]
[CustomAuthorize(DiplomaRoles.SchoolStaff, DiplomaRoles.StateAdultEdManagement, DiplomaRoles.SchoolAdmin, DiplomaRoles.StateAdmin)]
public ActionResult BulkEditStudentRecordsAdultEd(EditStudentAdultEdViewModel vm) //All other information from my view model gets through
{
var keys = vm.StudentKeys; //Empty
var DistrictCd = vm.DistrictCd; //Ok
var SchoolCd = vm.SchoolCd; //Ok
}
查看模型
public class EditStudentAdultEdViewModel
{
public EditStudentAdultEdViewModel()
{
StudentKeys = new Dictionary<string, string>();
}
public string DistrictCd {get; set;}
public string SchoolCd {get; set;}
public string IdentificationNbr{ get; set; }
public int DuplicateNbr { get; set; }
public Dictionary<string, string> StudentKeys { get; set; }
public string AdultEdAgencyCd { get; set; }
}
最佳答案
MVC 已经将提交的所有内容放入字典中。
public ActionResult BulkEditStudentRecordsAdultEd(FormCollection vm)
{
// to access an item, do this: vm["inputName"]
}
如果您希望默认模型绑定(bind)器为您绑定(bind)到不同的字典中,您可以通过使用正确名称的输入来实现:
<input type="hidden" name="vm[KeyString]" value="ValueString" />
关于c# - 将字典传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266173/