我非常擅长使用MVC模式,但我尝试做的是让用户输入一些数字,然后每次提交一个数字,它都会被添加到一个数字中。名单。然而,在按钮按下之间清除列表,我目前在控制器中有所有列表内容。
控制器
public class NumberController : Controller
{
List<int> numList = new List<int>();
// GET: Number
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult ProcessNumber(Number number)
{
int RNo = number.RNum;
numList.Add(RNo);
string sequenceList = "";
foreach (int num in numList) { sequenceList = sequenceList + ", " + num; }
ViewBag.Message = "Number " + RNo + " saved successfully!" + " This is your current sequence :" + sequenceList + " A total of " + numList.Count + "numbers.";
return View("Index");
}
}
然后在视图中我有了这个。
@model TechMVC.Models.Number
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm("ProcessNumber", "Number", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Number</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.RNum, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.RNum, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.RNum, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
<p>@ViewBag.Message</p>
</div>
</div>
</div>
}
看起来像这样:
我没有兴趣让它看起来很花哨,我还没有过分肯定MVC框架。我知道我已经将数据从用户发送到视图然后发送到控制器,但是我还在某个时候使用过该模型吗?我应该将列表存储在模型中还是视图中?
答案 0 :(得分:1)
您无法在控制器变量中保留这些值。 Web是无状态的,每个HTTP请求都会执行代码的新实例。因此,您需要在某处保留数据。
您可以使用会话状态或应用程序状态。欲了解更多信息:
在实际应用程序中,您绝对需要数据库存储。与哪个商店无关,你可以使用Sqlite,SQL Server,MySQL,XML文档或任何你想要的东西。如果您是.NET Web开发的新手,我建议您开始使用实体框架来满足您的数据访问需求。更多信息:
答案 1 :(得分:1)
您必须将数据存储在某处。例如,您可以将其存储在会话中
列表numList = null; int rNo = number.RNum; string sequenceList = string.Empty;
if (Session["NumList"] != null) { //session exist. set numList = session numList = Session["NumList"] as List<int>; } else { //session not exist. set numList as new numList = new List<int>(); } //add number to numList numList.Add(rNo); //set session = numList Session["NumList"] = numList; //make join oj numList sequenceList = String.Join(", ", numList.ToArray()); //set message in a ViewBag ViewBag.Message = $"Number {rNo} saved successfully!" + $" This is your current sequence : {sequenceList}" + $" A total of {numList.Count} numbers."; return View("Index");
我没有V,所以可能是错误