MVC 4 ForeignKey not working

本文关键字:working not ForeignKey MVC | 更新日期: 2023-09-27 17:57:56

我可以创建Contract,但如何获得contractID以创建Main?我尝试了很多不同的方法,但我似乎不明白这应该如何运作。我已经完成了MVC开发的大部分工作,但总是避免干扰ForeignKeys

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(FormContext form)
    {
        if (ModelState.IsValid)
        {
            Contract hc = new Contract();
            hc.CreatedDate = DateTime.Now;
            hc.CreatedBy = "TestSubject";
            db.Contracts.Add(hc);
            db.SaveChanges();
            return RedirectToAction("CreateMain");
        }
        return View();
    }

        //
    // GET: /HostedVoiceOrder/CreateMain
    public ActionResult CreateMain()
    {
        return View();
    }
    //
    // POST: /HostedVoiceOrder/CreateMain
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateMain(HostedVoiceMain hostedvoicemain)
    {
        if (ModelState.IsValid)
        {
            db.HostedVoiceMains.Add(hostedvoicemain);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View();
    }

以下是型号

    public class Main
{
    [Key]
    public int MainID { get; set; }
    public string MainNumber { get; set; }
    public string PortNativeExisting { get; set; }
    public string CompanyNameCallerID { get; set; }
    public string DirectoryListingName { get; set; }
    public string YPHVSIC { get; set; }
    public string VoicePortalDID {get;set;}
    public string AnywherePortalDID { get; set; }

    public string SignersName { get; set; }
    public int ContractID { get; set; }
    [ForeignKey("ContractID")]
    public virtual Contract Contract { get; set; }
}
public class Contract
{
    [Key]
    public int ContractID { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }        
}

MVC 4 ForeignKey not working

例如,您可以通过查询字符串传递新创建的合同的id。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormContext form)
{
    if(ModelState.IsValid)
    {
        Contract hc = new Contract();
        hc.CreatedDate = DateTime.Now;
        hc.CreatedBy = "TestSubject";
        db.Contracts.Add(hc);
        db.SaveChanges();
        return RedirectToAction("CreateMain", new { contractID = hc.ContractID });
    }
    return View();
}
public ActionResult CreateMain(int contractID)
{
    return View(new Main() {
                        ContractID = contractID
                    });
}

Main:的编辑器视图

@using(Html.BeginForm()) {
    ...
    @Html.HiddenFor(m => m.ContractID)
    ...
}