我创建了一个"创建"包含以下代码的页面。我知道这不是最好的做法,但我不确定如何做到这一点。这是代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Victim")] Case @case, Person person)
{
var caseVictims = @case.Victim;
db.Cases.Add(@case);
db.SaveChanges();
var caseId = @case.ID; //need this
if (caseVictims != null && caseVictims != "")
{
if (caseVictims.Contains(";"))
{ // { "First1,Last1;First2,Last2" }
string[] victims = caseVictims.Split(';');
foreach (var victim in victims)
{
person.CaseId = caseId;
person.Victim = true;
person.FullName = victim;
person.Case = null;
db.People.Add(person);
db.SaveChanges();
}
}
else
{
person.CaseId = caseId;
person.Victim = true;
person.FullName = caseVictims;
person.Case = null;
db.People.Add(person);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(@case);
}
我希望能够创建一个案例并使用该案例中的信息,例如@case.Victim
来填充"人员"表。现在它正常工作,除了它创建两个"案例"每次我点击提交。无论有多少受害者"就是这种情况。我有。如果我评论"受害者"部分它只按预期创建一个Case。谢谢你的帮助!
编辑: 这是模型
public partial class Person
{
public int ID { get; set; }
public int CaseId { get; set; }
public Nullable<bool> Victim { get; set; }
public string FullName { get; set; }
public virtual Case Case { get; set; }
}
public partial class Case
{
public int ID { get; set; }
public string Victim { get; set; }
public virtual ICollection<Person> People { get; set; }
}
答案 0 :(得分:1)
我能够让它按照我想要的方式工作。这是最终的代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Victim")] Case @case, Case lastCase, Person person)
{
var caseVictims = @case.Victim;
lastCase = @case;
db.Cases.Add(@case);
db.SaveChanges();
var caseId = @case.ID; //need this
if (caseVictims != null && caseVictims != "")
{
if (caseVictims.Contains(";"))
{ // { "First1,Last1;First2,Last2" }
string[] victims = caseVictims.Split(';');
foreach (var victim in victims)
{
person.CaseId = caseId;
person.Victim = true;
person.FullName = victim;
person.Case = lastCase;
db.People.Add(person);
db.SaveChanges();
}
}
else
{
person.CaseId = caseId;
person.Victim = true;
person.FullName = caseVictims;
person.Case = lastCase;
db.People.Add(person);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(@case);
}
感谢所有人的帮助! :)