尝试在 gridview 中编辑行C# ASP.NET MVC

问题描述

我正在尝试修改 gridview 的每一行,这是我第一次用 C# 编程并使用 ASP.NET MVC

这是我选择从数据库获取数据的方式(这是我的Index.cshtml):

@{
     ViewData["Title"] = "display Data";
     string[] TableHeaders = new string[] {"Address ID","Address Line","City","State Province ID","Postal Code","Spatial Location","Row ID","Modified Date"}; }
 
 <div class="table">
     <table class="table table-bordered table-hover">
         <thead>
             <tr>
                 @{
                     foreach (var head in TableHeaders)
                     {
                         <th>
                             @head
                         </th>
                     }
                 }
             </tr>
         </thead>
 
         <tbody>
             @{
                 if (Model != null)
                 {
                     foreach (var Data in Model)
                     {
                         <tr>
                             <td>@Data.AddressID</td>
                             <td>@Data.AddressLine</td>
                             <td>@Data.City</td>
                             <td>@Data.StateProvinceID</td>
                             <td>@Data.PostalCode</td>
                             <td>@Data.SpatialLocation</td>
                             <td>@Data.RowID</td>
                             <td>@Data.ModifiedDate</td>
                         </tr>
                     }
                 }
             }
         </tbody>
     </table> </div>

我想添加一个按钮以便能够修改每一行,我添加了这个:

<td>button value="EDIT" type="button" format class="btn btn-primary btn-edit">EDIT</button></td>

但我不明白如何获取每一行的 id 并编辑内容,我非常迷茫。


编辑 #1

这是我的 Address.cs 文件(在 MODELS 文件夹内:

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

namespace Data_Grid.Models
{
    public class Address
    {
        public string AddressID { get; set; }
        public string AddressLine { get; set; }
        public string City { get; set; }
        public string StateProvinceID { get; set; }
        public string PostalCode { get; set; }
        public string SpatialLocation { get; set; }
        public string RowID { get; set; }
        public string ModifiedDate { get; set; }
    }
}

这是我的 HomeController 文件

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Data_Grid.Models;
using System.Data.sqlClient;
namespace Data_Grid.Controllers
{
    public class HomeController : Controller
    {
        sqlCommand com = new sqlCommand();
        sqlDataReader dr;
        sqlConnection con = new sqlConnection();
        List<Address> addresses = new List<Address>();
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
            con.ConnectionString = Data_Grid.Properties.Resources.ConnectionString;
        }

        public IActionResult Index()
        {
            FetchData();
            return View(addresses);
        }
        private void FetchData()
        {
            if(addresses.Count > 0)
            {
                addresses.Clear();
            }
            try
            {
                con.open();
                com.Connection = con;
                com.CommandText = "SELECT TOP (1000) [AddressID],[AddressLine1],[City],[StateProvinceID],[PostalCode],[SpatialLocation],[rowguid],[ModifiedDate] FROM [AdventureWorks2019].[Person].[Address]";
                dr = com.ExecuteReader();
                while (dr.Read())
                {
                    addresses.Add(new Address() {AddressID = dr["AddressID"].ToString(),AddressLine = dr["AddressLine1"].ToString(),City = dr["City"].ToString(),StateProvinceID = dr["StateProvinceID"].ToString(),PostalCode = dr["PostalCode"].ToString(),SpatialLocation = dr["SpatialLocation"].ToString(),RowID = dr["rowguid"].ToString(),ModifiedDate = dr["ModifiedDate"].ToString()
                    });
                }
                con.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [responsecache(Duration = 0,Location = responsecacheLocation.None,NoStore = true)]
        public IActionResult Error()
        {
            return View(new Errorviewmodel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

解决方法

假设您的 HomeController 类中有这样的 get 和 post 方法。

public ActionResult UpdateAddress(int id)
{

    var _addresses = new List<Address>
    {
        new Address {AddressID = 1,AddressLine = "AddressLine1",City = "City1"},new Address {AddressID = 2,AddressLine = "AddressLine2",City = "City2"},new Address {AddressID = 3,AddressLine = "AddressLine3",City = "City3"},};


    // Get the address by id
    var address = _addresses.SingleOrDefault(x => x.AddressID == id);



    return View(address);
}

[HttpPost]
public string UpdateAddress(Address address)
{


    return "Updated";
}

在 TD 标签的末尾添加操作链接。像这样。

<tr>
    <td>@Data.AddressID</td>
    <td>@Data.AddressLine</td>
    <td>@Data.City</td>
    <td>@Data.StateProvinceID</td>
    <td>@Data.PostalCode</td>
    <td>@Data.SpatialLocation</td>
    <td>@Data.RowID</td>
    <td>@Data.ModifiedDate</td>
    <td>@Html.ActionLink("Edit","UpdateAddress","Home",new { id = Data.AddressID },new {@class = "btn btn-primary btn-edit" })</td>
</tr>

地址更新页面上的表单应该是这样的。

@model Address

@using (Html.BeginForm("UpdateAddress",FormMethod.Post))
{
    @Html.HiddenFor(x=>x.AddressID)
    <div>
        @Html.TextBoxFor(x => x.AddressLine)
        @Html.LabelFor(x => x.AddressLine,"AddressLine")
    </div>

    <div>
        @Html.TextBoxFor(x => x.City)
        @Html.LabelFor(x => x.City,"City")
    </div>

    <button type="submit">Submit</button>
}

当您单击 Submit 按钮时,将地址对象发送到 UpdateAddress Action 的 post 方法。