c# - 如何从 MVC 中的对象列表中添加和显示数据?
问题描述
我正在开发一个词法分析器,我想在 MVC 中的一个表上显示所有数据。但为了简化代码,我将添加一个示例来展示我想要实现的目标。我有一个logic.cs类,词法分析器将接收进入的字符串,并且我想根据词法分析器方法将项目添加到列表中。
这是我的代码:
控制器
Repository repo = new Repository();
logic logica = new logic();
public ActionResult Index()
{
var getrepo = repo.GetData();
return View(getrepo.ToList());
}
[HttpPost]
public ActionResult Index(string str) {
logica.Logic_t(str); //I send str parameter to the logic class
var getrepo = repo.GetData();
return View(getrepo.ToList());
模型
存储库.cs
public class Repository
{
public List<data_table> data = new List<data_table>() { };
public List<data_table> GetData() {
return data;
}
}
数据表.cs
public int Line { get; set; }
public string Token { get; set; }
逻辑.cs
Repository repo = new Repository();
public void Logic_t(string s)
{
int Line = 1;
repo.data.Add(new data_table { Line =Line , Token = " NUMBER" });
}
看法
@model IEnumerable<pruebaarray.Models.data_table>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<textarea rows="10" cols="50" class="textarea" name="str">
</textarea>
<input type="submit" value="send-to-logic" class="btn btn-primary"/>
}
<table class="table-bordered">
<tr>
<th>Line</th>
<th>Token</th>
</tr>
@foreach (var item in Model) {
<tr>
<th>@item.Line</th>
<th>@item.Token</th>
</tr>
}
</table>
这是我的最终观点:
我的代码没有错误,但是当我单击提交按钮时,表格中没有显示任何内容。我错过了什么?或者有什么问题?
PD:我的词法分析器逻辑具有递归方法,因此它将不断地将数据添加到列表中。
更新:我只是通过将 List 设置为static
解决方案
目前,您的表单不知道要定位哪个控制器或操作。
Html.BeginForm()
有几个重载。
例如:
BeginForm(HtmlHelper, String, String, Object, FormMethod, Object)
将开始标记写入响应并将操作标记设置为指定的控制器、操作和路由值。该表单使用指定的 HTTP 方法并包含 HTML 属性。
在此处检查过载
推荐阅读
- python - 类之外的函数是什么?
- python - 跟随我的鼠标但停留在圆圈上的弧线
- wordpress - 如何在wordpress中更改邮件到电子邮件
- python - 如何构建一个聊天机器人来回复相同的常见问题解答问题,该问题对不同公司的常见问题解答数据在 Rasa,Python 中具有不同的答案
- python - Crontab 启动 Python 脚本,但 SystemD 没有?
- azure - Azure AppInsights 中的 POST UpdateStuff [版本] 和 POST /api/v1/UpdateStuff 有什么区别
- reactjs - 无法在渲染中的方法内显示承诺数据
- javascript - 返回函数并作为表达式分配给变量的函数调用问题
- sql-server - 授予 SQL Sever 访问权限以连接到网络共享 - 无域
- android - 如何从 strings.xml 获取 DB sqlite 数据,所以当我更改语言环境时,所有数据都可以翻译