asp.net-mvc-3 – DropDownListFor – 不选择“Selected”值

关于DropDownListFor的另一个问题是不选择“Selected”值.
这里是代码:

模型:

public class CreateEditAccountModel
{
    [Required]
    [Display(Name = "Permission")]
    public int PermissionId { get; set; }
    public IEnumerable<SelectListItem> Permissions { get; set; }
}

控制器:

[HttpGet]
[Authorize]
public ActionResult EditAccount(int id)
{
    CreateEditAccountModel model = new CreateEditAccountModel();
    model.Permissions = PermissionsAll();
    return View("CreateEditAccount",model);
}

在这一点上,如果我在返回行上放了一个断点,那么model.Permissions包含正确的IEnumerable< SelectListItem>对象具有多个项目,只有一个,具有Selected = true.

视图:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.PermissionId,Model.Permissions)
}

呈现:

<select id="PermissionId" name="PermissionId">
    <option value="">-- Select --</option>
    <option value="1">Permission one</option>
    <option value="2">Permission two</option>
</select>

由于某些原因,在任何选项上没有选定的属性,并且选择了第一个选项.

任何帮助是赞赏.

UPDATE

它似乎与这个article有关系.为了总结本文的解决方案,我需要确保属性名称(@ html.DropDownList的第一个参数)与模型的任何现有属性不匹配.有人可以解释为什么会这样吗?

当我在视图中写入这样的时候,它会正确地下拉:

@Html.DropDownList("PermissionIdNotMatching",Model.Permissions)

但是,由于我实际上希望binder能够将select元素的名称与model属性相匹配,所以没有任何逻辑意义.否则我必须手动获取这样的值:Request.Form [“PermissionIdNotMatching”];

有人有什么想法吗?

看到接受的答案和第一个评论.

解决方法

好的,让我们讨论一下你的例子,当PermissionId是int时.您发布的类型CreateEditAccountModel的模型可以查看.创建此模型时,PermissionId等于0(int的默认值).而DropDownListFor在视图中获取此值.因此,您没有选择值.
当您使用字符串类型时,PermissionId的默认值为null,因此“DropDownListFor”取为SelectList的默认值.

在这种情况下,最好使用int?或Nullable< int>键入PermissionId.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....