如何在View中预览数据

时间:2018-04-30 15:50:26

标签: asp.net asp.net-mvc

我不太了解ASP.NET和C#,但我知道Laravel(php)。问题是如何在SQL Server数据的视图中foreach数据。我已经检查了数据库连接,我觉得这很好。在Laravel中,我只是将模型带到集合中并将其返回并foreach。在ASP.NET中,我被困住了。

控制器索引方法:

public IActionResult Index()
{
        var model = service.Get

        string connectionString = configuration.GetConnectionString("CustomDatabase");

        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        SqlCommand com = new SqlCommand("Select count(*) from Programy",connection);
        var count = (int)com.ExecuteScalar();

        ViewData["TotalData"] = count;
        connection.Close();

        return View();
}

查看:

@model IEnumerable<ClaimBased.Models.Program>
@{
    ViewData["Title"] = "Index";
}
<h2>Index</h2>
<h3>Total data: @ViewData["TotalData"]</h3>

<p>
    <a asp-action="Create">Create New</a>
</p>

<table class="table">
<thead>
    <tr>
        <th>
                @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
    }
</tbody>
 </table>

型号:

using System; 
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ClaimBased.Models
{
    public class Program
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }
    }
}

0 个答案:

没有答案