MVC5:检查DropDownList是否有Selection(InvalidOperationException)?

时间:2014-06-10 14:50:01

标签: c# asp.net-mvc drop-down-menu asp.net-mvc-5 invalidoperationexception

我正在使用BootStrap Switch在我的一个MVC5 / EF6项目视图中显示/隐藏2 Html.DropDownLists()

<input type="checkbox" value="12345" name="Sponsor-Organization" checked class="userCreate-BSSwitch" />

        <div style="margin-bottom: 15px">
            <div class="row switchOn">
                <div class="editor-label">
                    @Html.LabelFor(model => model.MemberOrgId, "Organization")
                </div>
                <div class="editor-field">
                    @Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { @class = "form-control", @id = "MemberOrgId" })
                    @Html.ValidationMessageFor(model => model.MemberOrgId)
                </div>
            </div>

            <div class="row switchOff">
                <dliv class="editor-label">
                    @Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
                </dliv>
                <div class="editor-field">
                    @Html.DropDownList("SponsorOrgId", ViewData["Sponsor"] as SelectList, String.Empty, new { @class = "form-control", @id = "SponsorOrgId" })
                    @Html.ValidationMessageFor(model => model.SponsorOrgId)
                </div>
            </div>
        </div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

<script type="text/javascript">
    jQuery(document).ready(function () {
        setTimeout(function () { $("#alert").alert('close'); }, 5000);
        $('.switchOff').addClass('hide');

    });
    $.fn.bootstrapSwitch.defaults.state = '';
    $.fn.bootstrapSwitch.defaults.onText = 'Member';
    $.fn.bootstrapSwitch.defaults.offText = 'Sponsor';
    $.fn.bootstrapSwitch.defaults.offColor = 'info';
    $.fn.bootstrapSwitch.defaults.animate = false;

    //$.fn.bootstrapSwitch.defaults.size = 'large';
    $(document).ready(function () {
        $('input:checkbox[name="Sponsor-Organization"]').bootstrapSwitch();
    });

    $('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
        var checked = state;
        if (checked) {
            $('.switchOn').removeClass('hide');
            $('.switchOff').addClass('hide');
            $('#SponsorOrgId').val("");
        }
        else {
            $('.switchOff').removeClass('hide');
            $('.switchOn').addClass('hide');
            $('#MemberOrgId').val("");
        }
    });

    $(document).ready(function () {
        $(".btn-danger").click(function () {
            var cancel = confirm("Are you sure? Entered data will be lost.")
            if (cancel != true) {
                event.preventDefault(); // cancel the event
            }
        });
    });

    //$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function(event, state) {
</script>

控制器创建()方法:

        // POST: Admin/UserManagement/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Id,property1, property2, etc...")] ApplicationUser applicationUser)
        {
            if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null))
            {
                ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists.");
                return View(applicationUser);
            }

            if (ModelState.IsValid)
            {
                ViewBag.headerTitle = "Create User";
                applicationUser.UserName = applicationUser.Email;
                IdentityResult result = await UserManager.CreateAsync(applicationUser, "r@nd0mP@$S");
                if (result.Succeeded) 
                {
                    await db.SaveChangesAsync();
                    return RedirectToAction("Index", "UserManagement");
                }
                else
                {
                    ModelState.AddModelError("", "Failed to Create User.");
                    var errors = string.Join(",", result.Errors);
                    ModelState.AddModelError("", errors);
                }
            }

            ModelState.AddModelError("", "Failed to Create User.");
            var errors1 = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToString();
            ModelState.AddModelError("", errors1);

            ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name", applicationUser.MemberOrgId);
            ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name", applicationUser.SponsorOrgId);
            if (applicationUser.MemberOrgId != null)
            {
                ViewBag.SwitchState = true;
            }
            else
            {
                ViewBag.SwitchState = false;
            }
            ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "State", applicationUser.MemberOrgId);

            // If we got this far, something failed, redisplay form
            return View(applicationUser);

        }

这使我能够确保只有1个DropDownList有一个选择,当我通过我的JavaScript隐藏当前DropDownList时清除当前选择。我现在需要的是在将新的身份用户保存到数据库之前确保在当前显示的列表中进行选择的方法。

现在,我的控制器正确识别何时未在任何一个列表中进行选择:

if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null))
            {
                ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists.");
                return View(applicationUser);
            }

但是,当返回视图而不是模型状态错误时,我立即在代码行@Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { @class = "form-control", @id = "MemberOrgId" })收到以下内容:

InvalidOperationException was unhandled by user code.

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'MemberOrgId'.

有人想过如何更好地处理这件事吗?

0 个答案:

没有答案