我正在努力创建一个"创建"用于将新结果插入表格的表单。我有一个映射到此表的模型,下面显示的三个中的第一个,以及另外两个我想用来显示下拉数据的模型,但是将结果绑定到APLayerID,BPlayerID和CourseID。
换句话说,我想要一个A PlayerNames,B PlayersNames和Courses的列表,它们映射到EditSingles中的APLayerID,BPlayerID和COurseID。
我已经尝试创建一个ViewModel,也在下面,其中包含所有这三个模型,然后将其传递给View,但我真的不确定我在做什么!
在我的控制器中,我有一个_model.SaveResults(EditSingles),如果我只是在视图中使用EditSingles,那么效果很好,但是我想显示玩家和课程的名称,这样更容易用于添加行,而不必记住ID号。
public class EditSingles
{
[Key]
public int GameID { get; set; }
public int APlayerID { get; set; }
public int BPlayerID { get; set; }
public int Score { get; set; }
public int Winner { get; set; }
public int GYear { get; set; }
public int CourseID { get; set; }
}
高尔夫球:
public class Golfer
{
[Key]
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string ImageURL { get; set; }
}
场
public class Courses
{
[Key]
public int CourseID { get; set; }
public string CourseName { get; set; }
public int CoursePar { get; set; }
public string CourseAddress { get; set; }
[DataType(DataType.Date)]
public DateTime DatePlayed { get; set; }
public string CourseInformation { get; set; }
}
视图模型
public class AdminModel
{
public IEnumerable<EditSingles> EditSingleResults { get; set; }
public IEnumerable<GolferDetails> GolferDetails { get; set; }
public IEnumerable<Courses> CourseDetails { get; set; }
}
答案 0 :(得分:1)
您需要一个视图模型,其中包含EditSingles
的相关属性以及Golfers
和Courses
public class EditSinglesVM
{
[Required(ErrorMessage = "Please select player A")]
[Display(Name = "Player A")]
public int APlayerID { get; set; }
....
[Required(ErrorMessage = "Please select a course")]
[Display(Name = "Course")]
public int CourseID { get; set; }
public IEnumerable<SelectListItem> PlayerList { get; set; }
public IEnumerable<SelectListItem> CourseList { get; set }
}
然后在GET方法中(假设您创建一个新记录)
public ActionResult EditSingles(int ID)
{
// Initialize your view model
EditSinglesVM model = new EditSinglesVM();
// Populate the SelectList's
ConfigureViewModel(model);
return View(model);
}
private void ConfigureViewModel(EditSinglesVM model)
{
model.PlayerList = db.Golfers().Select(g => new SelectListItem
{
Value = g.PlayerID.ToString(),
Text = string.Format("{0} {1}", g.FirstName, g.Surname)
});
model.CourseList = db.Courses().Select(c => new SelectListItem
{
Value = g.CourseID.ToString(),
Text = g.CourseName
});
}
并在视图中
@model EditSinglesVM
@using(Html.BeginForm())
{
@Html.LabelFor(m => m.APlayerID)
@Html.DropDownListFor(m => m.APlayerID, Model.PlayerList, "-Please select-")
@Html.ValidationMessageFor(m => m.APlayerID)
....
@Html.LabelFor(m => m.CourseID)
@Html.DropDownListFor(m => m.CourseID, Model.CourseList, "-Please select-")
@Html.ValidationMessageFor(m => m.CourseID)
<input type="submit" ... />
}
和POST方法
public ActionResult EditSingles(EditSinglesVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // repopulate SelectList's
return View(model(;
}
// Initialize a new data model
// Map the view model properties to it
// Save and redirect
}