外键没有填充MVC3

时间:2012-03-26 21:58:54

标签: c# asp.net asp.net-mvc-3 asp.net-mvc-3-areas

大家好我有以下代码:

public ActionResult Create(GameTBL gametbl)
        {
            if (ModelState.IsValid)
            {
                //First you get the gamer, from GamerTBLs
                var gamer = db.GamerTBLs.Where(k => k.UserName == User.Identity.Name).SingleOrDefault();
                //Then you add the game to the games collection from gamers
                gamer.GameTBLs.Add(gametbl);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

它给了我以下错误:

Error   1   'MvcApplication1.Controllers.GameController.Create(MvcApplication1.Models.GameTBL)': not all code paths return a value

这段代码试图将玩家的外键填入游戏表

我的控制器Gamer模型:

    public string UserName { get; set; }
    public int GamerID { get; set; }
    public string Fname { get; set; }
    public string Lname { get; set; }
    public string DOB { get; set; }
    public string BIO { get; set; } 

我的游戏控制器模型:

    public int GameID { get; set; }
    public string GameName { get; set; }
    public string ReleaseYear { get; set; }
    public string Cost { get; set; }
    public string Discription { get; set; }
    public string DownloadableContent { get; set; }
    public string Image { get; set; }
    public string ConsoleName { get; set; }
    public int GamerIDFK { get; set; }
    public byte[] UserName { get; set; }

3 个答案:

答案 0 :(得分:3)

只需在ModelState无效时返回视图。

public ActionResult Create(GameTBL gametbl)
    {
        if (ModelState.IsValid)
        {
            //First you get the gamer, from GamerTBLs
            var gamer = db.GamerTBLs.Where(k => k.UserName == User.Identity.Name).SingleOrDefault();
            //Then you add the game to the games collection from gamers
            gamer.GameTBLs.Add(gametbl);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(gametbl);
    }

这将使页面显示模型创建中的任何错误(假设您已经验证)。

答案 1 :(得分:0)

试试这个...... return语句应该在if语句之外...问题是当modelstate无效时你没有返回一个视图/动作结果......

public ActionResult Create(GameTBL gametbl)
    {
        if (ModelState.IsValid)
        {
            //First you get the gamer, from GamerTBLs
            var gamer = db.GamerTBLs.Where(k => k.UserName == User.Identity.Name).SingleOrDefault();
            //Then you add the game to the games collection from gamers
            gamer.GameTBLs.Add(gametbl);
            db.SaveChanges(); 
            return RedirectToAction("Index");               
        }
        return View(gametbl);
    }

答案 2 :(得分:0)

您知道,错误并非与ASP.Net MVC相关 - 在任何返回值的方法中都会出错。

错误消息not all code paths return a value就是这样 - 当方法签名表明它应该时,代码中有一条路径没有返回值。

在您的情况下,您的操作方法具有签名ActionResult Create(GameTBL gametbl),因此该方法的所有路径都必须返回ActionResult。在您的代码中,ModelState.IsValid为true时发生的路径返回ActionResult - 但在ModelState.IsValid为false的路径中没有返回任何内容。

其他答案为您提供了如何通过“ModelState.IsValid为假”路径返回ActionResult来更正代码的示例。

相关问题