首页 > 解决方案 > 如何从 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

标签: c#asp.net-mvc

解决方案


目前,您的表单不知道要定位哪个控制器或操作。

Html.BeginForm()有几个重载。

例如:

BeginForm(HtmlHelper, String, String, Object, FormMethod, Object)

将开始标记写入响应并将操作标记设置为指定的控制器、操作和路由值。该表单使用指定的 HTTP 方法并包含 HTML 属性。

在此处检查过载


推荐阅读