【问题标题】:Asp.net Mvc using Json How to Edit the RecordAsp.net Mvc 使用 Json 如何编辑记录
【发布时间】:2019-11-13 17:24:16
【问题描述】:

我正在使用 json 在 Asp.net MVC 中创建一个简单的 crud 系统。我需要更新记录。但我不知道该怎么做。我成功地从数据库中查看数据并传递给 Datatable。并成功添加记录。当我编辑记录时,我不知道如何从控制器传递值到目前为止我在下面写的东西。编辑(int Id)我只是这样尝试。数据没有传递到相关的文本框进行编辑。

enter image description here

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }
    lgschoolEntities1 dc = new lgschoolEntities1();

    public ActionResult GetStudents()
    {
        using (lgschoolEntities1 db = new lgschoolEntities1())
        {
            var student = db.courses.ToList();
            return Json(new { data = student }, JsonRequestBehavior.AllowGet);        
         }
    }

    [HttpPost]
    public ActionResult Save(course cou)
    {
        bool status = false;
        if (ModelState.IsValid)
        {
            using (lgschoolEntities1 dc = new lgschoolEntities1())
            {
                if (cou.id > 0)
                {
                    //Edit 
                    var v = dc.courses.Where(a => a.id == cou.id).FirstOrDefault();
                    if (v != null)
                    {
                        v.name = cou.name;
                        v.course1 = cou.course1;                 
                    }
                }
                else
                {
                    //Save
                    dc.courses.Add(cou);
                }
                dc.SaveChanges();
                status = true;
            }
        }
        return new JsonResult { Data = new { status = status } };

    }

    [HttpGet]
    public ActionResult Edit(int Id)
    {
        //Get the student from studentList sample collection for demo purpose.
        //Get the student from the database in the real application
        var std = dc.courses.Where(a => a.id == Id).FirstOrDefault();


        return new JsonResult { Data = new { std = std } };

     }

在我为查看数据库中的记录而编写的代码下方。当我查看记录时,如果我想编辑记录,请单击编辑按钮,相关数据将传递到相关文本框进行编辑。

function get_all() {
    $('#tbl-category').dataTable().fnDestroy();
    var oTable = $('#tbl-category').DataTable({
        "ajax": {
            "url": '/home/GetStudents',
            "type": "get",
            "datatype": "json"
        },
        "columns": [
            { "data": "name", "200px": true },
            { "data": "course1", "200px": true },

            {
                "data": "id", "width": "50px", "render": function (data) {

                     return '<button class="btn btn-xs btn-success" onclick="get_category_details(' + data + ')  ">Edit</button>';
                 }
             },
             {
                 "data": "id", "width": "50px", "render": function (data) {

                     return '<button class="btn btn-xs btn-primary" onclick="RemoveCategory(' + data + ')">Delete</button>';

                  }
              }
          ]
     })

 }

我正在使用相同的功能进行添加和编辑。

 function addProject() {
     var _url = '';
     var _data = '';
     var _method;   
     if (isNew == true) {
         _url = '/home/Save';
         _data = "{name: '" + $('#name').val() + "',course1: '" + $('#course1').val() + "'}";
        _method = 'POST';
     }
     else {
         _url = '/home/Edit',
         //    _data = "{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "', id: '" + id + "'}";
         _data = "{fname: '" + $('#fname').val() + "', age: '" + $('#age').val() + "', id:'" + ID + "'}";
         _method = 'POST';
     }
     console.log(_data);
     $.ajax({
         type: _method,
         url: _url,
         dataType: 'JSON',
         contentType: "application/json; charset=utf-8",
         data: _data,

         success: function (data) {

             alert("Success");

             get_all();
             $('#name').val("");
             $('#course1').val("");
             $('#name').focus();


             var msg;
             if (isNew) {
                 msg = "Data Created";

             }
             else {
                 msg = "Update Created";

             }
             $.alert({
                 title: 'Success!',
                 content: msg,
                 type: 'green',
                 boxWidth: '400px',
                 theme: 'light',
                 useBootstrap: false,
                 autoClose: 'ok|2000'
             });
         }
     });
 }

这就是我在单击编辑按钮时将值传递给相关文本框的方式。

function get_category_details(id) {
    $.ajax({
        type: 'POST',
        url:  '/home/Edit',
        dataType: 'JSON',
        data: "{id: '" + id + "'}",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
            //      $('body').animate({ scrollTop: 0 }, 1000);
            isNew = false;

            ID = data.d[0].id;
            $('#id').attr('value', data.d[0].id);
            $('#name').attr('value', data.d[0].name);
            $('#course1').attr('value', data.d[0].course1);


        }
    });
}

表格

<div class="row">
    @using (Html.BeginForm("save","home", FormMethod.Post, new { id= "popupForm" }))
    { 
         <div class="card-panel teal lighten-2 white-text" align="center">
             <h4> Registation</h4>
         </div>

         <div class="card-action">

         <label class="form-label">Name</label>

         <input type="text" id="name" name="name" class="form-control" placeholder="Name" required />

         </div>
         <div class="card-action">
             <label class="form-label">Course</label>
             <input type="text" id="course1" name="course1" class="form-control" placeholder="Course" required />
         </div>

         <div class="card" align="center">
             <button type="button" id="save" class="btn btn-info" onclick="addProject()">
                 Registation
             </button>
         </div>

     }
 </div>

 <div class="col s12 m6 offset-m4">
     <div class="panel-heading">
         <h3 class="panel-title">Current Team Members</h3>
     </div>

     <div class="panel-body">

         <table id="tbl-category" style="width:90%; margin:0 auto">
             <thead>
                 <tr>
                     <th>Name</th>
                     <th>Course</th>

                     <th>Edit</th>
                     <th>Delete</th>
                 </tr>

            </table>
        </div>
    </div>

这是我断点时显示的错误

enter image description here

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    你已经做对了,只是你需要告诉Entity Framework模型已经改变,你可以通过设置模型状态来做到这一点,将状态更改为EntityState.Modified

    如下图

    [HttpPost]
        public ActionResult Save(course cou)
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                using (lgschoolEntities1 dc = new lgschoolEntities1())
                {
                    if (cou.id > 0)
                    {
                        //Edit 
                        var v = dc.courses.Where(a => a.id == cou.id).FirstOrDefault();
                        if (v != null)
                        {
                            v.name = cou.name;
                            v.course1 = cou.course1;    
                            //you just need to add this line
                            dc.Entry(v).State = EntityState.Modified;             
                        }
                    }
                    else
                    {
                        //Save
                        dc.courses.Add(cou);
                    }
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
    
        }
    

    当您执行dc.Entry(v).State = EntityState.Modified; 时,您不仅将实体附加到数据库上下文,还将整个实体标记为脏且已更新。这意味着当您执行 context.SaveChanges() 时,EF 将生成一个更新语句,该语句将更新实体的所有字段。

    所以编辑也意味着更新数据库中的记录

    也看一些细节here

    编辑 还将javascript函数更改为

    function addProject() {
            var _url = '';
            var _data = '';
            var _method;   
            if (isNew == true) {
                _url = '/home/Save';
                _data = "{name: '" + $('#name').val() + "',course1: '" + $('#course1').val() + "'}";
                _method = 'POST';
            }
            else {
                _url = '/home/Save', //Change this line because you are using thte same method to save and edit in your controller
                //    _data = "{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "', id: '" + id + "'}";
                _data = "{fname: '" + $('#fname').val() + "', age: '" + $('#age').val() + "', id:'" + ID + "'}";
                _method = 'POST';
            }
            console.log(_data);
    
            //You ajax call here
            //The code below was commented to keep answer short
        }
    
        [HttpGet] //Change to get
        public JsonResult Edit(int Id)
        {
            return new JsonResult { Data = new { std = std } };
        }
    

    同时更改您在 javascript 中调用它的方式以及分配变量的方式

    function get_category_details(id) {
            $.ajax({
                type: 'GET',
                url:  '/home/Edit?Id=' + id,
                dataType: 'JSON',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                      console.log(data);
                    //      $('body').animate({ scrollTop: 0 }, 1000);
                    isNew = false;
    
                    ID = data.id;
                    $('#id').val(data.id);
                    $('#name').val(data.name);
                    $('#course1').val(data.course1);
                }
            });
        }
    

    【讨论】:

    • 我通过电子邮件发送给它先生。没有数据库。你能检查一下先生
    • 是的,先生,很好,非常感谢。先生,你能为我做删除的东西吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2014-03-28
    • 2011-05-13
    • 1970-01-01
    • 2015-06-25
    • 2010-11-02
    相关资源
    最近更新 更多