我的程序存在以下问题:我有一个 User 类,其中包含您可以学习的一系列课程。这些课程有一系列的培训日。我从 MySQL 数据库中获取所有值。我正在模型绑定我的用户类。一切都是正确的模型绑定,但是当我提交我选择的培训日时,它不会将值更改为 true。
更新: 切换到视图模型使其在单击提交时返回一个空视图模型。
课程:
public partial class User
{
/*insert User Properties*/
public virtual ICollection<Course> Courses { get; set; }
/*methods*/
}
public partial class Course
{
/*insert Course Properties*/
public virtual ICollection<Trainingday> Trainingdays{ get; set; }
public IEnumerable<Trainingday> GetTrainingdays()
{
IEnumerable<Trainingday> listDays = (from l in Trainingdays
where l.IsSelected
select l);
return listDays;
}
}
public partial class Trainingday
{
public int Id { get; set; }
public bool IsSelected { get; set; }
public DateTime Date { get; set; }
}
控制器:
private CourseViewModel model;
public ActionResult Course(User user, string code)
{
Course course = user.GetCourse(code); /*retrieves the course for specified code*/
model = new CourseViewModel();
model.Date = course.Date;
model.Title = course.Title;
model.Description = course.Description;
model.Trainingdays = course.Trainingdays;
return View("Course", model);
}
[HttpPost]
public ActionResult Trainingdays(CourseViewModel courseModel)
{
IEnumerable<Trainingday> trainingdays = courseModel.GetTrainingdays();
return View("Trainingdays", trainingdays);
}
视图模型:
public class CourseViewModel
{
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime? Date { get; set; }
public virtual ICollection<Trainingday> Trainingdays{get;set;}
public IEnumerable<Trainingday> GetTrainingdays()
{
IEnumerable<Trainingday> listDays = (from l in Trainingdays
where l.IsSelected
select l);
return listDays;
}
}
看法:
@model Models.Domain.CourseViewModel
@{
ViewBag.Title = "Course";
}
@using (Html.BeginForm("Trainingdays","Course", new{Model}))
{
<table>
<tr><td>Date</td><td>Selection</td></tr>
@foreach (var item in Model.Trainingdays)
{
<tr>
<td>
@Html.DisplayFor(x => item.Date)
</td>
<td>
@Html.CheckBoxFor(x => item.IsSelected)
</td>
</tr>
}
</table>
<input type="submit" value="Show selected trainingdays!" />
}
当我点击提交时,我所有的值都和以前一样。我一直在研究这个问题一段时间,我从其他人那里找到的解决方案似乎没有帮助。