我只是想将值绑定到下拉列表控件。我看不到任何例子,但它对我不起作用。请找到我的代码和错误,并帮我解决这个问题。
//我的模特
public class SubjectModel
{
public int selectedid {get;set;}
public List<SelectListItem> ddllist{get;set;}
public SubjectModel()
{
ddllist = new List<SelectListItem>();
}
}
//我的控制器
public ActionResult DropDownTest()
{
SubjectModel model = new SubjectModel();
model.ddllist.Add(new SelectListItem { Text = "Physics", Value = "1" });
model.ddllist.Add(new SelectListItem { Text = "Chemistry", Value = "2" });
model.ddllist.Add(new SelectListItem { Text = "Mathematics", Value = "3" });
model.selectedid = 0;
return View(model);
}
//我的观点
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DopDownBinding.Models.SubjectModel>"%>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>DropDownBinding</title>
</head>
<body>
<section id="ip">
<p>
<label for="timezone">Subjects</label>
@Html.DropDownListFor(model => model.selectedid, new SelectList(Model.ddllist, "SubCategoryId", "SubCategoryName", Model.selectedid))
</p>
</section>
</body>
执行此操作时出现此错误。
表达式树可能不包含动态操作
我是MVC的新手,如果出现问题,请帮我纠正。谢谢
答案 0 :(得分:0)
由于ddllist
类中的SubjectModel
属性为List<SelectListItem>
,因此您无需为new SelectList(Model.ddllist, "SubCategoryId", "SubCategoryName", Model.selectedid)
辅助对象的第二个参数执行@Html.DropDownListFor
。
更改此语法
@Html.DropDownListFor(
model => model.selectedid,
new SelectList(
Model.ddllist,
"SubCategoryId",
"SubCategoryName",
Model.selectedid))
到这个
@Html.DropDownListFor(model => model.selectedid, Model.ddllist)
您还需要删除第二行
<%@Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<DopDownBinding.Models.SubjectModel>"%>
并将此语法添加到第一行
@model DopDownBinding.Models.SubjectModel
答案 1 :(得分:0)
你在Razor中的下拉应该是
//Model.ddllist is selectlist for your dropdown
@Html.DropDownListFor(model => model.selectedid, Model.ddllist)