使用Json的Asp.net Mvc如何编辑记录

时间:2019-07-03 04:44:46

标签: asp.net asp.net-mvc

我正在使用json在Asp.net MVC中创建一个简单的Crud系统。我需要更新记录。但是我不怎么做。我成功地查看了数据库中的数据并将其传递给Datatable。并成功添加记录。当我编辑记录时,我不知道如何从控制器传递值,到目前为止我在下面写的内容。Edit(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 } };

     }

在我编写的用于查看数据库中记录的代码下面。当我查看记录时,如果要编辑记录,请单击“编辑”按钮,相关数据将传递到相关的textbooxs进行编辑。

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

1 个答案:

答案 0 :(得分: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将生成一条更新语句,该语句将更新实体的所有字段。

所以编辑也意味着更新Db中的记录

还要查看一些详细信息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);
            }
        });
    }