Mvc3 DropdownlistFor错误

时间:2013-04-04 10:18:46

标签: asp.net-mvc asp.net-mvc-3 c#-4.0 asp.net-mvc-4

我有一个包含组织列表的mvc3下拉列表。我可以使用下面的代码填写它。但是当我提交表单时,我得到的是Id而不是名称,相应的Id为空。

控制器

    ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
return view();

模型

public class SubscriberModel
    {
        public OrgnizationList Organization { get; set; }
        public RegisterModel RegisterModel { get; set; }
        public SubscriberDetails SubscriberDetails { get; set; }
    }
    public class OrgnizationList
    {
        [Required]
        public ObjectId Id { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Name")]
        public string Name { get; set; }
    }

查看 @

model FleetTracker.WebUI.Models.SubscriberModel
@using (Html.BeginForm((string)ViewBag.FormAction, "Account")) {
<div>
@Html.DropDownListFor(m => m.Organization.Name, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
</div>
}

enter image description here

当我改变它时tom =&gt; m.Organization.Id,然后模型状态将变为无效。

2 个答案:

答案 0 :(得分:1)

您真的需要返回名称而不是ID吗?如果是,则代替:

  

ViewBag.DropDownList = organizationModelList.Select(x =&gt; new   SelectListItem {Text = x.Name,Value = x.Id.ToString()});

这样做:

ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Name });

然后删除Required的{​​{1}}属性。如果OrgnizationList.Id是一个实体,我认为它是,那么你将遇到麻烦。我建议你有一个代表你输入的viewmodel。因此,您无需处理不必要的必填字段

但如果OrgnizationList不是唯一的呢?为什么不能只接受Name并将其保存在数据存储中?我假设您没有修改Id的名称。

<强>更新 如果你真的需要两个,那么将Id放在隐藏的字段上:

您的控制器方法

OrgnizationList

您的模型

ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Id });

您的观点

public class SubscriberModel
{
    public int OrganizationId { get; set; }
    // your other properties goeshere
}

需要一些js ......

<div>
    @Html.HiddenFor(m=>m.OrganizationId)
    @Html.DropDownListFor(m => m.Organization.Name, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
</div>

答案 1 :(得分:0)

我是用

做的
 $(document).ready(function () {
                $("#DropDownList").change(function () {
                    $("#Organization_Id").val($(this).val());
                    $("#Organization_Name").val($("#DropDownList option:selected").text());

                });
            }); 
    @Html.HiddenFor(m=>m.Organization.Id)
    @Html.HiddenFor(m=>m.Organization.Name)
    @Html.DropDownList("DropDownList", string.Empty)

控制器

ViewBag.DropDownList = new SelectList(organizationModelList, "Id", "Name");
相关问题