从视图访问控制器方法

时间:2014-01-06 17:14:57

标签: c# asp.net-mvc

我是C#和MVC的新手,我正在创建一个猜谜游戏,以便学习创建MVC产品所需的技能。我有View制作,我可以向控制器提交猜测没问题。我现在希望看到用户之前提交的所有猜测,但无法弄清问题是什么。

我的观点:

@model Prigmore2013_01.Models.GuessingGame

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<h2>Guessing Game</h2>
<p>Insert your 3 guesses into the textboxes below</p>
<form action="Exercise09/GuessTheDigits" method="post">
    <label for="guesses">Guess 1: @Html.TextBoxFor(x => x.Guesses[0], new { style = "width:12px", MaxLength = "1" }) Guess 2: @Html.TextBoxFor(x => x.Guesses[1], new { style = "width:12px", MaxLength = "1" }) Guess 3: @Html.TextBoxFor(x => x.Guesses[2], new { style = "width:12px", MaxLength = "1" })</label>
    <br />

    <label for="pastGuesses">Your Previous Guesses</label>
    <!-- Need to loop guesses -->

    <!-- End looping guesses -->
    <br />
    <button type="submit" name="Submit">Submit</button>
</form>
<form action="Exercise09/StartNewGame" method="post">
    <button type="submit" name="Submit">New Game</button>
</form>

我的控制器:

using Prigmore2013_01.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Prigmore2013_01.Tests
{
    public class Exercise09Controller : Controller
    {
        //
        // GET: /Exercise09/

        public ActionResult Index()
        {
            return View();
        }

        public ViewResult ShowPreviousGuesses()
        {
            if (HttpContext.Session["GameState"] == null)
            {
                HttpContext.Session["GameState"] = new GuessingGame();
            }

            GuessingGame theGame = this.Session["GameState"] as GuessingGame;
            return View("Index", theGame.Guesses);
        }

        public ViewResult ShowGuessesMade()
        {
            return View();
        }

        public ActionResult GuessTheDigits(List<int> guesses)
        {
            if (HttpContext.Session["GameState"] == null)
            {
                HttpContext.Session["GameState"] = new GuessingGame();
            }

            GuessingGame theGame = this.Session["GameState"] as GuessingGame;

            theGame.GuessTheHiddenDigits(guesses);

            return RedirectToAction("Index", theGame.Guesses);
        }

        public RedirectToRouteResult StartNewGame()
        {
            GuessingGame newTarget = this.Session["GameState"] as GuessingGame;
            newTarget.Target.Clear();
            var rand = new Random();

            for (int i = 0; i < 3; i++)
            {
                if(!newTarget.Target.Contains(rand.Next(1, 10)))
                {
                    newTarget.Target.Add(rand.Next(1, 10));
                }
            }

            return RedirectToRoute(new
            {
                controller = "Exercise09",
                action = "Index"
            });
        }
    }
}

我的模特:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Prigmore2013_01.Models
{
    public class GuessingGame
    {
        private Random _random;

        public GuessingGame()
        {
            this._random = new Random();
            this.Guesses = new List<Guess>();
            this.Target = new List<int>(){ 1, 2, 3 };
        }

        public List<int> Target { get; set; }
        public List<Guess> Guesses { get; set; }

        public List<Guess> ShowGuessesMade()
        {
            return Guesses;
        }
        public void NewGame()
        {
            this.Target.Clear();
            var count = 4;
            for (var i = 1; i < count; i++)
            {
                var swap = _random.Next(1, 9);

                if (!this.Target.Contains(swap))
                {
                    this.Target.Add(swap);
                }
            }
        }
        public void GuessTheHiddenDigits(List<int> guesses)
        {
            Guess g = new Guess() { Digits = guesses };
            //compare the lists
            var list = this.Target;
            var list2 = g.Digits;

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] == list2[i])
                {
                    g.RightDigitRightPosition++;
                }
            }
            //Now calculate how many digits in guesses are just plain wrong
            List<int> result = g.Digits.Except(this.Target).ToList();
            g.RightDigitWrongPosition = g.Digits.Count - result.Count - g.RightDigitRightPosition;

            //handle duplicates
            if (list.Count != list2.Distinct().Count())
            {
                // set thet right digit wrong position
                for (int i = 0; i < list2.Distinct().Count(); i++)
                {
                    g.RightDigitWrongPosition = i;
                }
            }
            this.Guesses.Add(g);
        }
    }
}

以前的尝试:

以前我尝试了以下方法; foreachfor循环: 以下内容不会循环并导致运行时错误,指出Object reference not set to an instance of an object.

@if(Model.Guesses != null)
    {
        foreach(var item in Model.Guesses)
        {
            Html.DisplayFor(x => x.Guesses.Count());
        }
    }

当我尝试下一个for loop时,var i = 0会导致错误Object reference not set to an instance of an object.

for(var i = 0; i < Model.Guesses.Count(); i++)
{
    Html.DisplayFor(x => x.Guesses.Count())
}

如何通过在我的视图中显示用户以前的猜测来查看?

1 个答案:

答案 0 :(得分:1)

由于您的视图是使用Prigmore2013_01.Models.GuessingGame强列入的,因此您应该将正确的对象传递给View方法:

public ViewResult ShowPreviousGuesses()
{
    ...
    return View("Index", theGame);
}

使用现在的ASP.NET MVC无法将Guesses列表转换为GuessingGame对象,导致Model为null。