MVC 4 ForeignKey无法正常工作

时间:2014-04-10 15:34:40

标签: c# asp.net-mvc-4

我可以创建合同但是如何获得继承的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; }        
}

1 个答案:

答案 0 :(得分:1)

例如,您可以通过查询字符串传递新创建的合约的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)
    ...
}