mvc4 DropdownList不设置选定的值

时间:2013-08-29 09:41:08

标签: c# asp.net-mvc-4 razor html-select

嗨,我有一个让我发疯的问题。我的项目的一个页面中有一个下拉列表,它应该像所有其他页面上的所有其他下拉列表一样,但它没有,我不知道为什么。

在这里,您将看到cshtml页面中的代码。这是正常的下拉:

<p>
    Specify a organisation to search in
    @Html.DropDownList("OrganisationList", new SelectList(ViewBag.OrganisationList, "ID", "Name", ViewBag.SelectedOrganisation))
</p>

在控制器中,我有一个绑定下拉列表的方法和一个调用视图的方法:

private void BindAllOrganisations()
{
    List<OrganisationModel> OrganisationList = new List<OrganisationModel> { new OrganisationModel { ID = null, Name = "Select" } };

    foreach (var Organisation in DatabaseConnection.DataContextRead.GetTable<Organisation>())
    {
        OrganisationList.Add(new OrganisationModel { ID = Organisation.OrganisationId, Name = Organisation.Name });
    }

    ViewBag.OrganisationList = OrganisationList;
}

/**
 * Loads the ManageUserView with all users from a specific organisation unit
 **/
[AzaraAuthorization(RequiredRoles = new[] { RolesEnum.Admin })]
public ActionResult ManageUsersFromOrgUnit(int Id)
{
    try
    {
        var orgUnit = organisationUnitManagement.GetSingleUnit(Id);
        List<AzaraUser> AzaraUserList = azaraUserManagement.GetAllUserFromOrganisationUnit(orgUnit);
        ViewBag.FromOrgUnits = Id;
        BindAllOrganisations();
        ViewBag.SelectedOrganisation = orgUnit.Organisation.OrganisationId;
        return View("ManageUsers", AzaraUserList);
    }
    catch (BusinessObjectNotRetrievableByIdException exc)
    {
        ExceptionHandling.BusinessObjectNotRetrievableByIdExceptionOccured(exc, "ManageUsersFromOrgUnit(int Id)", "ManageUsersController");
        return RedirectToAction("Index", "Home", new { Info = "A program error occured. The administrator get informed. Apologize the inconvenience." });
    }
}

我找不到问题。此外,如果我使用ViewBag.SelectedOrganisation替换页面上的1(我知道后面的数据库中存在值为1的模型),则会选择null的值。以下是列表的使用模型:

public class OrganisationModel
{
    public int? ID { get; set; }
    public string Name { get; set; }
}

可能有错误或我错过了什么?

0 个答案:

没有答案