简体   繁体   English

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

[英]Asp.net Mvc using Json How to Edit the Record

i am creating a simple crud system in Asp.net MVC using json. 我正在使用json在Asp.net MVC中创建一个简单的Crud系统。 i need to update the record. 我需要更新记录。 but i don't how to do it. 但是我不怎么做。 i successfully view the data from database and passing to Datatable. 我成功地查看了数据库中的数据并将其传递给Datatable。 and Successfully add the records. 并成功添加记录。 when i Edit the record i don't know how to pass the values from the controller what i tried so far i written below.Edit(int Id) i just tried like this way.data is not passing to the relavent textboxes for edit. 当我编辑记录时,我不知道如何从控制器传递值,到目前为止我在下面写的内容。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 } };

     }

Below the code i wrote for view the records from the database.when i view the record if i want to edit the record click edit button relavent data will be passing to the relvent textbooxs for edit. 在我编写的用于查看数据库中记录的代码下面,当我查看记录时如果要编辑记录,请单击“编辑”按钮,相关数据将传递给相关的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>';

                  }
              }
          ]
     })

 }

i am doing Add and Edit both doing at the Same Function. 我正在做添加和编辑都在相同的功能。

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

this how i am passing the values to the relavent textboxs when i click the edit button . 这就是我单击“编辑”按钮时将值传递到相关文本框的方式。

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


        }
    });
}

Form 形成

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

this is the error displayed when i break point 这是我断点时显示的错误

enter image description here 在此处输入图片说明

You are already doing it right just that you need to tell Entity Framework that the model has been changed, you do that by setting the model state, change the state to EntityState.Modified 您已经做对了,只是需要告诉Entity Framework模型已更改,您可以通过设置模型状态,将状态更改为EntityState.ModifiedEntityState.Modified

like as below 如下

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

    }

When you are doing dc.Entry(v).State = EntityState.Modified; 在执行dc.Entry(v).State = EntityState.Modified; , you are not only attaching the entity to you database context, you are also marking the whole entity as dirty and updated. ,您不仅将实体附加到数据库上下文,还将整个实体标记为已脏并已更新。 This means that when you do context.SaveChanges(), EF will generate an update statement that will update all the fields of the entity. 这意味着当您执行context.SaveChanges()时,EF将生成一条更新语句,该语句将更新实体的所有字段。

So Editing also means updating the records in the Db 因此,编辑还意味着更新Db中的记录

Also look at some details here 这里也看一些细节

EDIT Also change the javascript function to 编辑也将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 } };
    }

Also change the way you call it in your javascript and the way you assign the variables 还要更改您在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);
            }
        });
    }

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

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