簡體   English   中英

使用Json的Asp.net Mvc如何編輯記錄

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

我正在使用json在Asp.net MVC中創建一個簡單的Crud系統。 我需要更新記錄。 但是我不怎么做。 我成功地查看了數據庫中的數據並將其傳遞給Datatable。 並成功添加記錄。 當我編輯記錄時,我不知道如何從控制器傳遞值,到目前為止我在下面寫的內容。Edit(int Id)我只是這樣嘗試。數據沒有傳遞到相關的文本框進行編輯。

在此處輸入圖片說明

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>

這是我斷點時顯示的錯誤

在此處輸入圖片說明

您已經做對了,只是需要告訴Entity Framework模型已更改,您可以通過設置模型狀態,將狀態更改為EntityState.ModifiedEntityState.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中的記錄

這里也看一些細節

編輯也將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);
            }
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM