这里我尝试了以下代码,但我无法实现。 在下拉列表SelectListItem(“objItem”)的视图页面中,我可以看到下面提到的属性和值,但列表框没有选择“炼金术士”
ModelBindingControls.cshtml
<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);
}
答案 0 :(得分:-1)
而不是BookName我将属性更改为获奖书。现在它对我有用。
@Html.DropDownListFor(x => x.BookName, objItem,"Select Book", new { @id = "ddlBookName" })
我改为:
@Html.DropDownListFor(x => x.AwardedBook , objItem,"Select Book", new { @id = "ddlBookName" })