2013-04-04 74 views
0

我有一个mvc3下拉列表包含组织list.I能够填充使用下面的代码。但是当我提交表单时,我得到Id而不是名称和相应的Id为空。Mvc3 DropdownlistFor错误

控制器

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

当我改变它汤姆=>米组织.Id,那么模型状态将变为无效。

回答

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"); 
1

你确实需要返回的名称而不是Id吗?如果是,则代替该:

ViewBag.DropDownList = organizationModelList.Select(X =>新 SelectListItem {文本= x.Name,值= x.Id.ToString()});

做到这一点:

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

然后取出Required属性为OrgnizationList.Id。如果OrgnizationList是一个我认为是的实体,那么你会陷入麻烦。我建议你有一个代表你的意见的视图模型。所以你不必处理不必要的必填字段

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

UPDATE: 如果你真的需要双方再掖编号上一个隐藏字段:

你的控制器方法

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 
} 

您的看法

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

和一点需要JS的...

$("Organization_Name").change(function(){ 
    $("#OrganizationId").val($(this).val()); 
}); 
+0

@Von。我只有名字,但我想要Id和Name。 – 2013-04-04 10:26:15

+0

查看我更新的答案,只需根据需要调整即可。 – 2013-04-04 10:33:09