【问题标题】:How to send Data from Controller to cshtml with ASP.NET Core 3.0如何使用 ASP.NET Core 3.0 将数据从控制器发送到 cshtml
【发布时间】:2020-04-09 00:19:30
【问题描述】:

我正在使用自己的数据库,我想从我的数据库中获取描述并将数据放入 html 中的表中。 但是我真的找不到任何有用的东西,而且我真的不知道如何将数据从控制器传输到视图 - 或者如何将数据从视图请求到控制器。

这就是我的控制器的样子:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult getTableNames()
        {
            DatabaseItemDescription databaseItemDescription = new DatabaseItemDescription();
            databaseItemDescription.Name = "abc";
            databaseItemDescription.Description = "def";
            databaseItemDescription.Content = "ghi";

            return View(databaseItemDescription); //Does this work?
        }
    }
}

这就是我的 Index.cshtml 的样子:

@page
@model DatabaseItemDescription

<h1>DatabaseEditTest</h1>


<table id="buttonTable">
    <thead>

    </thead>
</table>

<table id="descriptionTable"
       class="table table-bordered table-condensed table-striped">
    <thead>
        <tr>
            <th>Action</th>
            <th>Name</th>
            <th>Description</th>
            <th>Content</th>
        </tr>
    </thead>

    <tbody>

    </tbody>
</table>


<script>
    function getFirstTableDesc() {
        $("#firstTable thead").remove();
        $("#buttonTable thead").append("<tr>" + "<th><button onclick='updateTableDesc()'>Update</button></td>" + "<th><button onclick='refreshTableDesc()'>Refresh</button></td>" + "<tr>");
    }

    function updateTableDesc() {
        $("#descriptionTable tbody").empty();

        //here i want to read the Data from the Controller and insert it into the table like:
        //Fetch Data from Controller
        //$("#descriptionTable tbody").append("<tr>" + "<td><button onclick='Edit()'>Edit</button></td>" + "<td>${Name}</td>" + "<td>${Description}</td>" + "<td>${Content}</td>" + "</tr>");
    }
    }

    function refreshTableDesc() {

    }
</script>

如果有人可以帮助我,我将非常感激! 谢谢

【问题讨论】:

    标签: asp.net-mvc asp.net-core model-view-controller razor controller


    【解决方案1】:

    假设您在代码中有一个强类型视图(@modelm 小写),

    @model DatabaseItemDescription
    

    您可以在视图中使用Model 属性来读取来自Controller 的信息。

    返回视图(databaseItemDescription); //这个有用吗?

    您正在将DatabaseItemDescription 类型的对象作为Model 传递给您的View。您可以通过我的Model 访问此信息,因此,您可以试试这个:

    <tr>
        <th> Maybe you add some links here to perform actions like edit/delete </th>
        <th>@Model.Name</th>
        <th>@Model.Description</th>
        <th>@Model.Content</th>
    </tr>
    

    只是从控制器中读取信息并将其显示在视图上。如果需要,您可以添加更多属性。

    【讨论】:

    • 这也适用于列表吗?因为我会有一个包含 15 个条目的列表,这就是为什么我很困惑如何在表中插入数据
    • 我已经更新了我的答案。在这里,我们正在讨论如何从控制器发送数据以查看和显示它。要坚持下去,我认为最好再问一个问题。
    【解决方案2】:

    试试这个:

    <tr>
        <th>@Model.Action</th>
        <th>@Model.Name</th>
        <th>@Model.Description</th>
        <th>@Model.Content</th>
    </tr>
    

    【讨论】:

      【解决方案3】:

      您已经混合了这些东西,您可以更改两种方法并使其工作,如果您希望您的视图按照@Felipe Oriani 的建议进行更改,您还需要更改您的 Index 方法并从中返回数据作为模型

          public IActionResult Index()
          {
              DatabaseItemDescription databaseItemDescription = new DatabaseItemDescription();
              //prepare model
      
              return View(databaseItemDescription);
          }
      

      然后您可以使用@Modal.Name、@Model.Description 等进行绑定。

      您尝试从 JS 获取数据的其他方法如下,使用 Ajax 调用和绑定响应获取数据

      function updateTableDesc() {
          //here i want to read the Data from the Controller and insert it into the table like:
          //Get data using Ajax call to "Home/getTableNames" and bind using JS
      }
      

      并更改您的 getTableNames 方法以返回 Json

          public IActionResult getTableNames()
          {
              DatabaseItemDescription databaseItemDescription = new DatabaseItemDescription();
              //prepare model
              return Json(databaseItemDescription); //this will work
          }
      

      【讨论】:

        【解决方案4】:

        好的,所以关于你的情况,有一个非常好的插件叫做DataTables,你可以使用它来显示来自ControllerView 上的数据。您可以参考以下代码 sn-p 来满足您的要求:

        你的Model

        namespace Test.Models
        {
            public class DatabaseItemDescription 
            {
                public string Name { get; set; }
                public string Description { get; set; }
                public string Content { get; set; }
            }
        }
        

        你的Controller

        using System.Collections.Generic;
        using System.Linq;
        using System.Threading.Tasks;
        using Microsoft.AspNetCore.Mvc;
        using Test.Models;
        
        namespace Test.Controllers
        {
            public class HomeController : Controller
            {
                public IActionResult Index()
                {
                    return View();
                }
        
                public JsonResult getTableNames()
                {
                    List<DatabaseItemDescription> databaseItemDescription = new List<DatabaseItemDescription>();
        
                    //Example of how you could initialize your list
                    databaseItemDescription.Add(new DatabaseItemDescription
                    {
                     Name = "abc",
                     Description = "def",
                     Content = "ghi"
                    });
        
                    databaseItemDescription.Add(new DatabaseItemDescription
                    {
                     Name = "efg",
                     Description = "hij",
                     Content = "klm"
                    });
        
                    return Json(databaseItemDescription, JsonRequestBehavior.AllowGet);
                }
            }
        }
        

        你的View 看起来像:

        @{
            ViewBag.Title = "Home Page";
            Layout = null;
        }
        
        <html>
        <head>
            <meta name="viewport" content="width=device-width" />
            <title>Index</title>
            @*<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
                <script src="~/Scripts/jquery-3.4.1.js"></script>
                <link href="~/Content/bootstrap4.min.css" rel="stylesheet" />
                <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
                <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>*@
        
            <!-- CDN LINKS-->
            <link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.3.1/cerulean/bootstrap.min.css" rel="stylesheet" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
            <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
            <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
        </head>
        <body>
            <div class="jumbotron">
                <h1>DataTable Example</h1>
                <p class="lead">A project dedicated to data table example in MVC</p>
            </div>
            <br />
            <center>
                <div style="width: auto; border: 1px solid black; padding: 3px" ;>
                    <table id="dataTable">
                        <thead>
                            <tr>
                                <th style="width: auto; border: 1px solid black; padding: 3px" ;>Name</th>
                                <th style="width: auto; border: 1px solid black; padding: 3px" ;>Description </th>
                                <th style="width: auto; border: 1px solid black; padding: 3px" ;>Content </th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </center>
            <script type="text/javascript">
                    $(document).ready(function () {
                        $.ajax({
                            "url": "@Url.Action("getTableNames", "Home")",
                            "method": "post",
                            "dataType" : "json",
                            success: function (data) {
                                $('#dataTable').DataTable({
                                    paging: true,
                                    sort: true,
                                    searching: true,
                                    data:data,
                                    columns: [
                                        { 'data': 'Name'},
                                        { 'data': 'Description' },
                                        { 'data': 'Content' }
                                    ]
                                });
                            }
                        });
                    });
            </script>
        </body>
        </html>
        

        为了您的刷新和更新,您可以参考插件的官方文档,或者您可以创建自定义按钮并将它们使用AJAX绑定到您的Controller方法。希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-21
          • 1970-01-01
          • 2020-04-25
          • 2013-09-28
          • 2021-09-03
          • 2020-10-05
          • 1970-01-01
          • 2021-10-23
          相关资源
          最近更新 更多