很抱歉,如果这是一个重复的问题,我扫描的相关问题,并没有看到任何明显的。

我使用与实体对象的EditModel,带有两个沿着SelectLists。问题是,一旦我达到我的POST操作,两个下拉菜单的SelectedValues仍然是相同的默认值,我在构造函数的模型设定,无论是什么其实我在浏览器中进行选择。

我的构造函数设置为SelectedValues一些默认值,但它们只是0和“”(这是不是在下拉菜单有效值)。我有一种感觉周围的问题围绕莫名其妙,但我会透露更多的细节。

下面是该模型的一个精简版:

public class UserAccountModel 
{

    public UserAccount UserAccountData { get; set; } // Entity from EF
    public SelectList Organizations { get; set; }
    public SelectList Roles { get; set; }

    public UserAccountModel() : this(null)
    {
    }


    public UserAccountModel(UserAccount obj)
    {
        UserAccountData = (obj == null) ? new UserAccount() : obj;

        // default selected value
        int orgChildId = (UserAccountData.Organization == null) ? 0 : UserAccountData.Organization.ID;
        string roleChildId = (UserAccountData.Role == null) ? "" : UserAccountData.Role.Name;

        // go get the drop down options and set up the property binding
        using (UserAccountRepository rep = new UserAccountRepository())
        {
            Organizations = new SelectList(rep.GetOrganizationOptions(), "ID", "ID", orgChildId);
            Roles = new SelectList(rep.GetRoleOptions(), "ID", "Name", roleChildId);
        }
    }

    public void UpdateModel()
    {
        UserAccountData.Organization = Organizations.SelectedValue as Organization;
        UserAccountData.Role = Roles.SelectedValue as Role;
    }
}

这是在视图的下拉框部分:

                <div class="field">
                <label for="ID">Organization:</label>
                <%= Html.DropDownList("ID", Model.Organizations) %>
            </div>

            <div class="field">
                <label for="Name">Role:</label>
                <%= Html.DropDownList("Name", Model.Roles) %>
            </div>

我可能已经在这里做了一些愚蠢和明显。使用ViewData字典的时候,但我找不到太多的例子试图用直模型SelectLists结合的例子是更加直截了当。

任何帮助是非常感谢!

克里斯

有帮助吗?

解决方案

选择元件只回发的选择它的实际值。在这种情况下,该参数将在服务器/控制器ID(组织)和名称(角色)接收回来。您使用的更新动作模型都应包含这些作为属性或您的控制器动作应该直接接受它们作为参数。该模型的列表将不会被重新填充 - 和名称不无论如何匹配

通过将修改模型:

public int ID { get; set; }
public string Name { get; set; }

用控制器动作为:

public ActionResult Update( UserAccountModel userAccount )
{
    ...
}

请注意,如果有一个验证错误,你需要重新填充选择列表的属性(重建菜单)。

其他提示

您简单地忘了ID属性的导航路径:)

<%= Html.DropDownList("Organization.ID", Model.Organizations) %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top