Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

Trying to edit row in a gridview (C# ASP.NET MVC)

I am trying to modify each row of a gridview, this is my first time programming in C# and using ASP.NET MVC

This is the way i chose to obtain to fetch the data from the database (this is my 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>

I wanted to add a button in order to be able to modify each row, i added this:

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

but i don't understand how can i obtain the id of each row and edit the content, i'm super lost.


EDIT #1

This is my Address.cs file (inside MODELS folder:

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

This is my HomeController file

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 });
        }
    }
}
question from:https://stackoverflow.com/questions/65885940/trying-to-edit-row-in-a-gridview-c-asp-net-mvc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's say you have get and post methods in your HomeController class like this.

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

Add action links at the end of the TD tags. Like this.

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

The form on the address update page should be something like this.

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

When You click the Submit button, sends the address object to the post method of UpdateAddress Action.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...