使用MVC访问从另一个视图传递的数据时遇到麻烦
本文关键字:数据 遇到 麻烦 访问 MVC 另一个 视图 使用 | 更新日期: 2023-09-27 17:53:18
我试图使用MVC将数据从一个视图传递到另一个视图。我正在尝试做一个简单的猜谜游戏,在第一个视图中,我们输入一系列数字,然后在第二个视图中,我们尝试猜测数字。我能够将值存储在我的模型中,但我在另一个视图上的js脚本中访问它们/使用它们时遇到了麻烦。对不起,如果这是太多的代码,MVC的很难寻求帮助,而不显示全范围的代码。当我进入第二个视图猜测数字时,它不识别@ViewBag.(model => model.Low)
,它显示Load is not defined
pubblic class Range
{
public int High
{
get
{
if (HttpContext.Current.Session["High"] == null)
{
HttpContext.Current.Session["High"] = 3;
}
return (int)HttpContext.Current.Session["High"];
}
set
{
HttpContext.Current.Session["High"] = value;
}
}
public int Low
{
get
{
if (HttpContext.Current.Session["Low"] == null)
{
HttpContext.Current.Session["Low"] = 1;
}
return (int)HttpContext.Current.Session["Low"];
}
set
{
HttpContext.Current.Session["Low"] = value;
}
}
}
控制器public class GuessingGameController : Controller
{
public ActionResult EnterRange()
{
return View();
}
[HttpPost]
public ActionResult EnterRange(Range range)
{
int high = range.High;
int low = range.Low;
return View(range);
}
public ActionResult GuessNumber()
{
return View();
}
}
View 1: Enter Range
@model GameMVC.Models.Range
@using (Html.BeginForm("EnterRange", "GuessingGame"))
{
<center>
<h2>Lets play a game.</h2>
Enter A Range of Numbers:
<br />
Low: @Html.TextBoxFor(m => m.Low)
<br />
High: @Html.TextBoxFor(m => m.High)
<br />
<input type="submit" value="Enter"/>
<p>
@Html.ActionLink("Now, To the Game", "GuessNumber", "GuessingGame")
</p>
</center>
}
View 2: Guess Number
@model GameMVC.Models.Range
<script language="JavaScript">
var myNum, count;
function Load() {
document.game.status.value = "Please set range of numbers and press the Start button.";
document.game.number.focus();
}
function Round(scale) {
var dd = new Date();
return((Math.round(Math.abs(Math.sin(dd.getTime())) * 8.71 * scale) % scale));
}
function myRange() {
var to = 1 + 1 * @ViewBag.(model => model.Low);
count = 0;
myNum = Round(to);
while (myNum < @ViewBag.(model => model.High);)
myNum = Round(to);
document.game.status.value = "Please guess a number, enter it, and press Guess.";
}
function Guess() {
var numberGuess = document.game.number.value;
count++;
if (numberGuess < myNum) alert("My number is greater than " + numberGuess + ".");
else if (numberGuess > myNum) alert("My number is less than " + numberGuess + ".");
else alert("It takes you " + count + " attempts to guess this number");
}
</script>
<body onload=" Load() ">
<div style="text-align: center;">
<form name=game>
Guess: <input type="text" name="number" size=10>
<p>
<br/>
<input type="button" value="Guess" onclick=" Guess() ">
</p>
@Html.Label("status")
</form>
</div>
</body>
代替@ViewBag.(model => model.Low)
,您可以尝试使用@Model.Low
没有为"GuessAction"视图提供模型实例。您需要将"Range"的实例传递给"GuessNumber"视图。由于您正在访问session中的值,因此您可以简单地传递一个新实例。
public ActionResult GuessNumber()
{
return View(new Range());
}
然后在javascript中,你可以简单地以@Model的方式访问数据。High和@Model。低
如果您只需要一个请求,您也可以使用TempData来存储高值和低值。