0

こんにちは、私は次のコードを持っています:

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

このコードが行おうとしているのは、ゲーマーの外部キーをゲーム テーブルに入力しようとしていることです。

私のコントローラーゲーマーのモデル:

    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; }
4

3 に答える 3

0

ご存知のように、このエラーは実際には ASP.Net MVC に関連するものではありません。値を返すメソッドで発生するエラーです。

このエラー メッセージnot all code paths return a valueは、値を返さないコードのパスが存在することを意味しています。

あなたの場合、アクション メソッドには署名があるActionResult Create(GameTBL gametbl)ため、メソッドを通るすべてのパスはActionResult. あなたのコードでは、ModelState.IsValid true のときに発生するパスは - を返しますが、 false ActionResultのパスには何も返されません。ModelState.IsValid

ModelState.IsValid他の回答では、「 is false 」パスを介して ActionResult を返すことでコードを修正する方法の例を示しています。

于 2012-03-26T22:53:27.810 に答える
0

これを試してください... returnステートメントはifステートメントの外にある必要があります...問題は、モデル状態が有効でない場合にビュー/アクションの結果を返さないことです...

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);
    }
于 2012-03-26T22:02:01.160 に答える