【发布时间】:2014-12-25 22:59:14
【问题描述】:
我有两张表,Location 和 Job
当我想创建新工作时,我可以从位置表中填充的下拉列表中选择位置。
我的创建视图:
public ActionResult Create(CreateJobViewModel model)
{
model.Locations = repository.GetAllLocations()
.Select(x => new SelectListItem { Text = x.State, Value = x.LocationId.ToString() })
.ToList();
return View(model);
}
和我的视图模型:
public class CreateJobViewModel
{
public Job Job { get; set; }
public IList<SelectListItem> Locations { get; set; }
public int SelectLocationId { get; set; }
}
这一切都很好,但是我如何从下拉框中获取选定的值,然后将该值保存在 Job 表的外键字段中?
我的帖子操作如下所示:
[HttpPost]
[Authorize(Roles = "Employer")]
[ValidateAntiForgeryToken]
public ActionResult Create(Job job)
{
repository.AddJob(job);
return RedirectToAction("Create");
}
post 动作使用 Job 实体,get 动作使用 CreateJobViewModel,在我之前的项目中,我只创建或显示,我从未遇到过这样的情况。
我正在考虑在视图之间传递模型???
在我的创建视图中,我不知道应该使用哪个模型,视图模型“CreateJobViewModel”还是“Job”实体?
@model foo.CreateJobViewModel
或
@model foo.Job
如何链接这两个模型???
【问题讨论】:
标签: asp.net-mvc entity-framework model-view-controller model