C# 尝试编辑gridview中的行(C ASP.NET MVC)

C# 尝试编辑gridview中的行(C ASP.NET MVC),c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我正在尝试修改gridview的每一行,这是我第一次用C和ASP.NETMVC编程 这是我选择从数据库获取数据的方式这是我的Index.cshtml: 这是我的HomeController文件 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc

我正在尝试修改gridview的每一行,这是我第一次用C和ASP.NETMVC编程

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

这是我的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";
}

@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>
}
在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>
地址更新页面上的表单应该是这样的

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";
}

@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>
}

当您单击“提交”按钮时,将地址对象发送到UpdateAddress操作的post方法。

嘿,伙计,你好吗?我正在检查!朋友,我不明白:你想在这里做什么:{新地址{AddressID=1,AddressLine=AddressLine1,城市=City1},新地址{AddressID=2,AddressLine=AddressLine2,城市=City2},新地址{AddressID=3,AddressLine=AddressLine3,城市=City3};我写它只是为了作为一个例子。您需要删除它并编辑代码:var address=\u addresses.SingleOrDefaultx=>x.AddressID==id;通过id从您的地址注册的地方获取地址数据库等。保持警惕,编辑我的帖子。!我刚刚更新了我的帖子。你会怎么改变它?。在索引视图pageIndex.cshtml中,如果您想使用标记,可以使用以下代码将id参数添加到按钮:使用此代码时编辑,路由模式如下:模式:{controller=Home}/{action=Index}/{id?};,您可以从Startup.cs文件中进行检查。然后,单击按钮后,它将重定向到主控制器中的编辑操作方法,因此,请尝试添加编辑操作并首先创建视图。以下是一些有关Asp.net Core CRUD操作的相关教程,您可以参考它们:和。
@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>
}