假设下面是我的视图模型类。
public class MainViewModel
{
public List<Student> Students { get; set; }
public int SelectedState = 0;
}
public class Student
{
public int ID = 0;
public string Name = "";
public int StateID = 0;
public List<States> States { get; set; }
}
public class States
{
public int ID = 0;
public string Name = "";
}
现在我怎么能用名为States of students class的嵌套属性绑定下拉列表?
@Html.DropDownListFor(x => x.SelectedState new SelectList(Model.Students.States, "ID", "Name", Model.SelectedState), "-- Select States--", new { id = "cboState", @class = "edit-mode" })
这不起作用SelectList(Model.Students.States, "ID", "Name", Model.SelectedState)
如何引用此Model.Students.States
请与代码示例讨论此问题。每个学生都与州有关系。
答案 0 :(得分:1)
检查出来:
XML
但最好在Controller中的ViewBag中保存States List:
@Html.DropDownListFor(x => x.SelectedState, new SelectList(Model.Students.FirstOrDefault().States, "ID", "Name", Model.SelectedState), "-- Select States--", new { id = "cboState", @class = "edit-mode" })
在视图上:
ViewBag.States = (_context or _serviceLayer).(States or GetStates()).Select(s => new SelectListItem { Value = s.ID, Text = s.Name, Selected = s.ID == viewModel.SelectedState }).ToList();
请求编辑:
型号:
@Html.DropDownListFor(x => x.SelectedState, (List<SelectListItem>)ViewBag.States, "-- Select States--", new { id = "cboState", @class = "edit-mode" })
控制器:
namespace MyProject.Models
{
public class ViewInfo
{
public int StateID { get; set; }
}
public class Student
{
public int ID { get; set; }
public string FullName { get; set; }
public int StateID { get; set; }
}
public class State
{
public int ID { get; set; }
public string Name { get; set; }
}
}
观点:
using MyProject.Models;
namespace MyProject.Controllers
{
public class StudentsController : Controller
{
private MyDBEntities _context;
public StudentsController()
{
this._context = new MyDBEntities();
}
// StudentsController
public ActionResult Index()
{
ViewBag.ViewInfo = new ViewInfo { StateID = 1 };
ViewBag.StateID = _context.States.Select(s => new SelectListItem { Value = s.ID, Text = s.Name }).ToList();
return View(_context.Students.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ViewInfo viewInfo)
{
ModelState.Clear();
ViewBag.ViewInfo = viewInfo;
ViewBag.StateID = _context.States.Select(s => new SelectListItem { Value = s.ID, Text = s.Name, Selected = s.ID == viewInfo.StateID }).ToList();
return View(_context.Students.Where(s => s.StateID == viewInfo.StateID).ToList());
}
}
}