0

I have a mvc3 dropdownlist containing Organization list.I am able to fill that using the code below.But when I submit the form, I am getting Id instead of name and the corresponding Id is null.

Controller

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

Model

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; }
    }

View @

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

When I change it tom => m.Organization.Id, then the modelstate will change to not valid.

4

2 に答える 2

1

Id の代わりに名前を返す必要がありますか? はいの場合、これの代わりに:

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

これを行う:

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

Required次に、 の属性を削除しますOrgnizationList.IdOrgnizationListが実体だと思うなら、あなたはトラブルに巻き込まれるでしょう。入力を表すビューモデルを用意することをお勧めします。したがって、不要な必須フィールドを処理する必要はありません。

しかし、Nameが一意でない場合はどうなるでしょうか。Idをそのまま受け入れて、データ ストアに保存できないのはなぜですか? の名前を変更していないOrgnizationListと思います。

更新: 本当に両方が必要な場合は、隠しフィールドに Id を入れます:

あなたのコントローラーメソッド

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());
});
于 2013-04-04T10:23:38.570 に答える
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");
于 2013-04-05T07:59:32.260 に答える