如何设置Html ListBoxFor的选定属性

本文关键字:ListBoxFor 属性 Html 何设置 设置 | 更新日期: 2023-09-27 18:26:55

这里我尝试了下面的代码,但无法实现。在下拉列表SelectListItem("objItem")的视图页面中,我可以看到下面提到的属性和值,但列表框没有选择"炼金师"

ModelBindingControls.cs.html

  <div>
   @{
       List<SelectListItem> objItem = new List<SelectListItem>();
       SelectListItem selectList = null;
       foreach(var item in Model.BookName){
           selectList = new SelectListItem();
           selectList.Text = item.Books;
           selectList.Value = item.Books;
           if(item.Books == Model.AwardedBook){
               selectList.Selected = true;   
           }
           objItem.Add(selectList);
       }
  }
 @Html.DropDownListFor(x => x.BookName, objItem,"Select Book", new { @id = "ddlBookName" })
</div>

ObjItem值为

    [0] Index
    Selected =  true
    Text    =   "The Alchemist"
    Value   =   "The Alchemist"
    [1] Index
    Selected =  false
    Text    =   "The Davinci Code"  
    Value   =   "The Davinci Code"
    [2]Index
    Selected =  false
    Text    =   "The Harry Potter"  
    Value   =   "The Harry Potter"

型号:

public class AuthorDetailsModel
{
    public List<AllBookDetails> BookName { get; set; }
    public string AwardedBook { get; set; }
}
public class AllBookDetails
{
    public string Books { get; set; }
}

控制器:

public ActionResult ModelBindingControls()
{
    AuthorDetailsModel objModel = new AuthorDetailsModel();          
    objModel.AwardedBook = "The Alchemist";
    List<AllBookDetails> listBookObj = new List<AllBookDetails>();
    AllBookDetails objDetails = new AllBookDetails();
    objDetails.Books = "The Alchemist";
    listBookObj.Add(objDetails);
    objDetails = new AllBookDetails();
    objDetails.Books = "The Davinci Code";
    listBookObj.Add(objDetails);
    objDetails = new AllBookDetails();
    objDetails.Books = "The Harry Potter";
    listBookObj.Add(objDetails);
    objModel.BookName = listBookObj;
    return View(objModel);
}

如何设置Html ListBoxFor的选定属性

我将属性改为Awarded book,而不是BookName。现在它对我有效。

@Html.DropDownListFor(x => x.BookName, objItem,"Select Book", new { @id = "ddlBookName" }) 

我改为:

@Html.DropDownListFor(x => x.AwardedBook , objItem,"Select Book", new { @id = "ddlBookName" })