簡體   English   中英

嘗試在 gridview 中編輯行(C# ASP.NET MVC)

[英]Trying to edit row in a 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 class 中有 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", "Home", 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>
}

當您單擊提交按鈕時,將地址 object 發送到 UpdateAddress Action 的 post 方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM