当我发布时,使用 SelectList 中的值填充模型上的属性
我正在构建一个 Asp.net MVC 2 应用程序。
我有一个名为 Team 的实体,它通过公共属性映射到另外两个名为 Gender 和 Grade 的实体。
public class Team
{
public virtual int Id { get; private set; }
public virtual string CoachesName { get; set; }
public virtual string PrimaryPhone { get; set; }
public virtual string SecondaryPhone { get; set; }
public virtual string EmailAddress { get; set; }
public virtual Grade Grade { get; set; }
public virtual Gender Gender { get; set; }
}
我有一个看起来像这样的 ViewModel。
public class TeamFormViewModel
{
public TeamFormViewModel()
{
Team = new Team();
Grade = new SelectList((new Repository<Grade>()).GetList(),"ID", "Name",Team.Grade);
Gender = new SelectList((new Repository<Gender>()).GetList(), "ID", "Name", Team.Gender);
}
public Team Team { get; set; }
public virtual SelectList Grade { get; set; }
public virtual SelectList Gender { get; set; }
}
我的表单按照我的预期呈现。当我调试 Create 方法时,我发现我的 Team 对象上的 Gender 和 Grade 属性为 NULL。
[HttpPost, Authorize]
public ActionResult Create(Team team)
{
try
{
if (ModelState.IsValid)
{
(new Repository<Team>()).Save(team);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
我做错了什么?
谢谢, 埃里克
I'm building an Asp.net MVC 2 application.
I have an entity called Team that is mapped via public properties to two other entities called Gender and Grade.
public class Team
{
public virtual int Id { get; private set; }
public virtual string CoachesName { get; set; }
public virtual string PrimaryPhone { get; set; }
public virtual string SecondaryPhone { get; set; }
public virtual string EmailAddress { get; set; }
public virtual Grade Grade { get; set; }
public virtual Gender Gender { get; set; }
}
I have a ViewModel that looks like this.
public class TeamFormViewModel
{
public TeamFormViewModel()
{
Team = new Team();
Grade = new SelectList((new Repository<Grade>()).GetList(),"ID", "Name",Team.Grade);
Gender = new SelectList((new Repository<Gender>()).GetList(), "ID", "Name", Team.Gender);
}
public Team Team { get; set; }
public virtual SelectList Grade { get; set; }
public virtual SelectList Gender { get; set; }
}
My form renders as I would expect. When I debug the Create method I see that the Gender and Grade properties are NULL on my Team object.
[HttpPost, Authorize]
public ActionResult Create(Team team)
{
try
{
if (ModelState.IsValid)
{
(new Repository<Team>()).Save(team);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
What am I doing wrong?
Thanks,
Eric
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您发布并绑定回视图模型类而不是实体类。为您的视图模型类创建一个扩展方法,该方法将返回您的实体类。这是一些工作代码:
最后是视图:
I recommend that you post and bind back to a view model class rather than your entity class. Create an extension method for your view model class that will return your entity class. Here's some working code:
And finally, the view: