我正在尝试将我的数据库中的新记录添加到多个相关表中,这些表都具有作为PK的ID和其他表的ID作为FK。我的方法是基于NerdDinner教程,但是当涉及多个表时,我找不到有关如何在数据库中添加新记录的任何示例。
由于某种原因尝试保存新记录时,ModelState.IsValid失败。我尝试添加它们,如下所示,并单独更新每个表,但这不起作用。
我是MVC,.NET和编程的新手,无法弄清楚我做错了什么。任何帮助表示赞赏。
[HttpPost]
public ActionResult Create(Team team)
{
Team t = team;
UpdateModel(t);
if (ModelState.IsValid)
{
teamRepository.AddTeam(t);
teamRepository.Save();
return RedirectToAction("Details", new { id = t.TeamID });
}
return RedirectToAction("Create");
}
这是我正在使用的ViewModel
public class TeamViewModel
{
//Properties
public Team team { get; set; }
public IQueryable<Department> departmentsList { get; set; }
public IQueryable<Team> teamList { get; set; }
public SelectList countriesList { get; set; }
public Country country { get; set; }
//Constructors
public TeamViewModel()
{
}
public TeamViewModel(IQueryable<Team> teams)
{
teamList = teams;
}
public TeamViewModel(TeamViewModel vm)
{
team = vm.team;
departmentsList = vm.departmentsList;
}
public TeamViewModel(TeamViewModel vm, Country c)
{
team = vm.team;
team.CountryID = c.CountryID;
}
public TeamViewModel(TeamViewModel vm, IEnumerable<Country> countries)
{
team = new Team();
countriesList = new SelectList(countries, "CountryID", "ShortName");
}
}
如果需要,这就是视图
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<div class="editor-label"><%: Html.LabelFor(m => m.team.ShortName) %></div>
<div class="editor-field"><%: Html.TextBoxFor(m => m.team.ShortName) %><%: Html.ValidationMessageFor(m => m.team.ShortName, "*") %></div>
<div class="editor-label"><%: Html.LabelFor(m => m.team.FullName)%></div>
<div class="editor-field"><%: Html.TextBoxFor(m => m.team.FullName)%><%: Html.ValidationMessageFor(m => m.team.FullName, "*")%></div>
<div class="editor-label"><%: Html.LabelFor(m => m.team.DateEstablished)%></div>
<div class="editor-field"><%: Html.TextBoxFor(m => m.team.DateEstablished)%><%: Html.ValidationMessageFor(m => m.team.DateEstablished, "*")%></div>
<div class="editor-label"><%: Html.LabelFor(m => m.team.City)%></div>
<div class="editor-field"><%: Html.TextBoxFor(m => m.team.City)%><%: Html.ValidationMessageFor(m => m.team.City, "*")%></div>
<div class="editor-label"><%: Html.LabelFor(m => m.team.Country) %></div>
//The misspelled field
//<div class="editor-field"><%: Html.DropDownListFor(model => model.team.Country, Model.countriesList, "<--Select Country-->") %></div>
//The corrected field
<div class="editor-field"><%: Html.DropDownListFor(model => model.team.CountryID, Model.countriesList, "<--Select Country-->") %></div>
</fieldset>
<p>
<input type="submit" value="Save" />
</p>
答案 0 :(得分:1)
首先,你使用的是什么Repository ORM?其次,为什么要将字段重新映射到新的Team对象。 Mvc已经为你做过这个,我认为你不需要这样做。如果您使用的是NHibernate,那么它可能与设置国家ID而不是国家/地区对象有关。如果您有一张国家/地区表,那么您可能会有一个国家/地区,因此NH会寻找以下内容
team.Country.Id
AND NOT
team.CountryId
看着你的观点就是这样。如果我是你,我会重新映射Team对象,已经完成了。打破行动并检查国家/地区对象是什么。
希望这有帮助