将字典传递给控制器

Passing a dictionary to a controller

我有一个 ViewModel,我正试图将其传递给我的包含字典的控制器。我能够让所有内容在视图中正确显示,但是当我到达 post 到我的控制器时,我从来没有让 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>  
}

控制器

[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"]
}

如果您希望默认模型绑定器为您绑定到不同的字典,您可以通过输入正确的名称来实现:

<input type="hidden" name="vm[KeyString]" value="ValueString" />