簡體   English   中英

下拉列表不起作用

[英]Drop down list isn't working

控制器:

   OnePersonAllInfoViewModel vModel = new OnePersonAllInfoViewModel();
  vModel.PreferredContactType = new PreferredContactType();


ViewBag.PrefContactTypes = new SelectList(dbEntities.PreferredContactTypes
                                  .OrderBy(pct => pct.PreferredContactTypeID),
                                   "PreferredContactTypeID", "PreferredContactType1",
                                   vModel.PreferredContactType.PreferredContactTypeID);

視圖:

<div class="editor-label">
        @Html.LabelFor(model => model.PreferredContactType.PreferredContactTypex)
    </div>

        @Html.DropDownListFor(model => model.PreferredContactType.PreferredContactTypeID, 
       ViewBag.PrefContactTypes as SelectList)

我在回發時收到此錯誤...沒有類型為“ IEnumerable”的ViewData項目具有鍵“ PreferredContactType.PreferredContactTypeID”

有什么想法嗎? 謝謝!

如果重新顯示相同的視圖,則在HttpPost控制器操作中,必須以與GET操作相同的方式重新填充ViewBag.PrefContactTypes屬性:

[HttpPost]
public ActionResult Process(OnePersonAllInfoViewModel model)
{
    ViewBag.PrefContactTypes = ...
    return View(model);
}

另外,您似乎已經定義了一些帶有ViewModel后綴的類。 這使讀者相信您正在應用程序中使用視圖模型,並且在下一行中使用ViewBag 為什么? 為什么不充分利用視圖模型及其強類型呢?

像這樣:

public class OnePersonAllInfoViewModel
{
     public int PreferredContactTypeID { get; set; }
     public IEnumerable<PreferredContactType> PrefContactTypes { get; set; }
}

然后在您的GET操作中:

public ActionResult Index()
{
    var model = new OnePersonAllInfoViewModel();
    model.PrefContactTypes = dbEntities
        .PreferredContactTypes
        .OrderBy(pct => pct.PreferredContactTypeID)
        .ToList();
    return View(model);
}

然后查看:

@Html.DropDownListFor(
    model => model.PreferredContactTypeID, 
    Model.PrefContactTypes
)

和POST動作:

[HttpPost]
public ActionResult Index(OnePersonAllInfoViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the model is invalid => we must redisplay the same view =>
        // ensure that the PrefContactTypes property is populated
        model.PrefContactTypes = dbEntities
            .PreferredContactTypes
            .OrderBy(pct => pct.PreferredContactTypeID)
            .ToList();
        return View(model); 
    }

    // the model is valid => use the model.PreferredContactTypeID to do some
    // processing and redirect
    ...

    // Obviously if you need to stay on the same view then you must ensure that 
    // you have populated the PrefContactTypes property of your view model because
    // the view requires it in order to successfully render the dropdown list.
    // In this case you could simply move the code that populates this property
    // outside of the if statement that tests the validity of the model

    return RedirectToAction("Success"); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM