简体   繁体   English

如何使用 asp.net MVC 在 GridView 中编辑数据?

[英]How to edit data in GridView using asp.net MVC?

I am binding data to the gridview from SQL server but having some issues with the Edit.我正在将数据从 SQL 服务器绑定到 gridview,但在编辑时遇到了一些问题。

Here is my model code:这是我的模型代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Data.Entity;

namespace Gridview_BugTracker.Models
{
    public class BugTracker_DataHelper
      {

        public static List<BugTracker_DataHelper> GetList{get;set;}

          public string ProjectId { get; set; }
          public string projectName { get; set; }           
          public string Description { get; set; }
           public  string status { get; set; }         
        }     

   }

Here is my controller code这是我的控制器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Gridview_BugTracker.Models;
using System.Data.SqlClient;
using System.Data.Entity;

namespace Gridview_BugTracker.Controllers
{
    public class ProjectsController : Controller
    {
        //
        // GET: /Projects/


        public ActionResult Index()
        {
            var bugedlist = GetList(); 
            return View(bugedlist);
        }
        [HttpGet]
        public ActionResult Edit(int projectId)
        {
             BugTracker_DataHelper bugedit = new BugTracker_DataHelper();           
             var edit = EditList();
             bugedit.ProjectId =Convert.ToString(projectId);
             return View(edit);      
        }

        public List<BugTracker_DataHelper> GetList()
        {
            var modelList = new List<BugTracker_DataHelper>();
            using (SqlConnection conn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BugTracker;Data Source=SSDEV6\SQLEXPRESS"))
            {
                conn.Open();
                SqlCommand dCmd = new SqlCommand("Select * from Projects", conn);
                SqlDataAdapter da = new SqlDataAdapter(dCmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                conn.Close();
                for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    var model = new BugTracker_DataHelper();
                    model.ProjectId = ds.Tables[0].Rows[i]["ProjectId"].ToString();
                    model.projectName = ds.Tables[0].Rows[i]["projectName"].ToString();
                    model.Description = ds.Tables[0].Rows[i]["Description"].ToString();
                    model.status = ds.Tables[0].Rows[i]["Status"].ToString();
                    modelList.Add(model);
                }
            }
            return modelList;
        }

     [HttpPost]   
    public ActionResult EditList()
        {
            var editlist = new List<BugTracker_DataHelper>();
            using (SqlConnection editconn=new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BugTracker;Data Source=SSDEV6\SQLEXPRESS"))
            {
                editconn.Open();
                var modeledit = new BugTracker_DataHelper();
                SqlCommand ecmd = new SqlCommand("EditGetList", editconn);
                ecmd.CommandType = CommandType.StoredProcedure;
                ecmd.Parameters.Add("@projectID", SqlDbType.Int).Value = modeledit.ProjectId;
                Object prjid = ecmd.ExecuteNonQuery();
                editconn.Close();                 

                editlist.Add(modeledit);
            }
            return View(editlist);
        }

Gridview Code网格视图代码

 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Gridview_BugTracker.Models.BugTracker_DataHelper>>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
    <h2>Index</h2>
<table>
    <tr>         
        <th>
            ProjectName
        </th>

        <th>
           Status
        </th>       

    </tr>

 <% foreach (var item in Model) { %> 

    <tr> 

        <td> 
            <%:Html.LabelForModel(item.projectName) %> 
        </td> 

        <td>
         <%:Html.LabelForModel(item.status) %>
        </td>

         <td>
            <%: Html.ActionLink("Edit", "Edit", new { projectId = item.projectName})%> |
            <%: Html.ActionLink("Details", "Details", new { projectId = item.Description })%> |
            <%: Html.ActionLink("Delete", "Delete", new { projectId = item.status })%>
        </td>

        </tr>

       <%} %>

</table>
    </div>
</body>
</html>

Edit page code:编辑页面代码:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/SiteMaster.Master" Inherits="System.Web.Mvc.ViewPage<Gridview_BugTracker.Models.BugTracker_DataHelper>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    editindex
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>editindex</h2>


    <fieldset>
        <legend>EDit</legend>        

        <div class="editor-label">
           <%:  Html.LabelFor(Model => Model.ProjectId) %>
        </div>
        <div class="editor-field">
           <%: Html.EditorFor(model => model) %>
           <%:  Html.ValidationMessageFor(model => model.projectName) %>
        </div>

        <div class="editor-label">
           <%: Html.LabelFor(model => model.Description) %>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.Description) %>
            <%: Html.ValidationMessageFor(model => model.Description)%>
        </div>


         <div class="editor-label">
           <%:  Html.LabelFor(model => model.status) %>
        </div>
        <div class="editor-field">
          <%:   Html.EditorFor(model => model.status) %>
          <%:    Html.ValidationMessageFor(model => model.status) %>
        </div>   


        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
</asp:Content>

When i click the edit button I am getting the following error.当我单击编辑按钮时,我收到以下错误。

Server Error in '/' Application. “/”应用程序中的服务器错误。

The parameters dictionary contains a null entry for parameter 'projectId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'Gridview_BugTracker.Controllers.ProjectsController'.参数字典包含“Gridview_BugTracker.Controllers.ProjectsController”中方法“System.Web.Mvc.ActionResult Edit(Int32)”的不可空类型“System.Int32”的参数“projectId”的空条目。 An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.可选参数必须是引用类型、可空类型或声明为可选参数。 Parameter name: parameters Description: An unhandled exception occurred during the execution of the current web request.参数名称:parameters 描述:当前web请求执行过程中发生了未处理的异常。 Please review the stack trace for more information about the error and where it originated in the code.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

Can anyone please help?有人可以帮忙吗?

I believe your problem may be in the following line.我相信您的问题可能在以下行。

 <%: Html.ActionLink("Edit", "Edit", new { projectId = item.projectName})%>

Your edit action is expecting an Int but you are passing it what I am assuming is a string.您的编辑操作需要一个 Int 但您正在传递它,我假设它是一个字符串。 So its never binding correctly and therefore you end up with a null projectId.所以它永远不会正确绑定,因此你最终会得到一个 null projectId。

Hope this helps.希望这可以帮助。

ProjectName is declared as string
      public string projectName { get; set; }  

While editing the item you should be passing an int but you are passing a string在编辑项目时,您应该传递一个 int 但您传递的是一个字符串

<%: Html.ActionLink("Edit", "Edit", new { projectId = item.projectName})%>
public ActionResult Edit(int projectId)
{
     BugTracker_DataHelper bugedit = new BugTracker_DataHelper();           
     var edit = EditList();
     bugedit.ProjectId =Convert.ToString(projectId);
     return View(edit);      
}

I think Your problem lies in the method, the method should be rewritten as below:我认为您的问题在于方法,该方法应重写如下:

public ActionResult Edit(int projectId)
{
     BugTracker_DataHelper bugedit = new BugTracker_DataHelper();           
     bugedit.ProjectId =Convert.ToString(projectId);
     var edit = EditList();
     return View(edit);      
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM