2013-04-04 72 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