简体   繁体   English

.NET Core MVC 在加载视图时显示数据

[英].NET Core MVC display data upon loading of view

In a .NET 6 MVC, i have a controller that perform retrieval of login information from external system, and after a user login on 1.cshtml, it will redirect user to 2.cshtml which auto display user past transactions in a table, which i uses a foreach loop.在 .NET 6 MVC 中,我有一个控制器从外部系统检索登录信息,在用户登录 1.cshtml 后,它将用户重定向到 2.cshtml,它会自动在表中显示用户过去的交易,这我使用 foreach 循环。 The first part works fine but i cant get the 2.cshtml to work, is there any sample for such scenarios?第一部分工作正常,但我无法让 2.cshtml 工作,是否有针对此类场景的示例? The retrieval of login info and user past transactions are placed in a single controller file, the retrieval works fine but just cant get the data to display on 2.cshtml.登录信息的检索和用户过去的交易被放置在一个控制器文件中,检索工作正常但无法让数据显示在 2.cshtml 上。 Thanks in advance.提前致谢。

The 2.cshtml should display user past transaction automatically upon the page is loaded. 2.cshtml 应该在页面加载时自动显示用户过去的交易。

There is a foreach loop in 2.cshtml, which has null error (object to set to an instance): 2.cshtml中有一个foreach循环,出现null错误(object to set to an instance):

@foreach (var r in Model)
                                {
                                    <tr>
                                        <td>@r.Title</td>
                                    </tr>
                                }

This is the Index method in 2Controller.cs:这是 2Controller.cs 中的 Index 方法:

public IActionResult Index()
    {
        List<dynamic> myList = new List<dynamic>();
        myList.Add("qwe");
        myList.Add("asd");


        return View(myList);
    }

And this is the login method in the main controller:这是主控制器中的登录方法:

public IActionResult Login(string email, string password)
    {
        if (CallExternalSystem(email) == true)
        {
            HttpContext.Session.SetString("email", email);
            return View("2");
        }
        else
        {
            ViewBag.error = "Invalid Account";
            return View("Index");
        }
    }

Full code of 2.cshtml: 2.cshtml的完整代码:

@model List<2>
@{
<table class="table table-striped table-bordered table-hover" id="data-table">
    <thead>
        <tr>
            <th>Col Header1</th>
        </tr>
    </thead>
    <tbody>
        @*<tr>
    <td>test data1</td>
    </tr>*@
        @foreach (var r in Model)
        {
            <tr>
                <td>@r.ToString()</td>
            </tr>
        }
    </tbody>
</table>

Your loop should only try to render @r because in your controller you are only adding strings.你的循环应该只尝试呈现@r因为在你的控制器中你只是添加字符串。

@foreach (var r in Model)
{
   <tr>
      <td>@r</td>
   </tr>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM