想对父网格和子网格分别进行 ech 的 crud 操作

Posted

技术标签:

【中文标题】想对父网格和子网格分别进行 ech 的 crud 操作【英文标题】:Want to do crud operation separately ech for parent grid and child grid 【发布时间】:2020-08-29 00:30:02 【问题描述】:
$(function() 

    $("#jqGrid").jqGrid(
        url: "/Student/GetStudents",
        datatype: 'json',
        mtype: 'Get',
        colNames: ['StudentId', 'FirstName', 'LastName', 'Gender', 'Class'],
        colModel: [
                key: true,
                hidden: true,
                name: 'StudentId',
                index: 'StudentId',
                editable: true
            ,
            
                key: false,
                name: 'FirstName',
                index: 'FirstName',
                editable: true
            ,
            
                key: false,
                name: 'LastName',
                index: 'LastName',
                editable: true
            ,
            
                key: false,
                name: 'Gender',
                index: 'Gender',
                editable: true,
                edittype: 'select',
                editoptions: 
                    value: 
                        'M': 'Male',
                        'F': 'Female',
                        'N': 'None'
                    
                
            ,
            
                key: false,
                name: 'Class',
                index: 'Class',
                editable: true,
                edittype: 'select',
                editoptions: 
                    value: 
                        '1': '1st Class',
                        '2': '2nd Class',
                        '3': '3rd Class',
                        '4': '4th Class',
                        '5': '5th Class'
                    
                
            
        ],
        pager: jQuery('#jqControls'),
        rowNum: 10,
        sortname: 'StudentId',
        sortorder: 'asc',
        rowList: [10, 20, 30, 40, 50],
        height: '100%',
        viewrecords: true,
        subGrid: true,
        iconSet: "fontAwesome",
        multiSort: true,
        sortable: true,
        loadonce: true,
        additionalProperties: ['Class', 'ClassLang'],
        autoencode: true,
        cmTemplate: 
            autoResizable: true
        ,
        autoresizeOnLoad: true,
        autowidth: true,
        autoResizing: 
            //resetWidthOrg: true,
            compact: true
        ,
        caption: 'Students Records',
        emptyrecords: 'No Students Records are Available to Display',
        jsonReader: 
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        ,
        multiselect: false,
        subGridRowExpanded: function(subgrid_id, row_id) 

            var subgrid_table_id;
            subgrid_table_id = subgrid_id + "_t";
            jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
            jQuery("#" + subgrid_table_id).jqGrid(
                //url: "/Student/GetStudentsMarks?RowId=" + row_id,
                // data:  'RowId': row_id ,
                datatype: function(pdata) 
                    getDataSubGrid(pdata, row_id);
                ,
                mtype: 'Get',
                colNames: ['Id', 'StudentId', 'SubjectId', 'Subject', 'Marks'],
                colModel: [
                        key: true,
                        hidden: true,
                        align: "right",
                        name: 'Id',
                        index: 'Id',
                        editable: true
                    ,
                    
                        key: true,
                        hidden: true,
                        align: "right",
                        name: 't.StudentsId.StudentId',
                        index: 't.StudentsId.StudentId',
                        editable: true
                    ,
                    
                        key: true,
                        hidden: true,
                        align: "right",
                        name: 'SubjectId',
                        index: 'SubjectId',
                        editable: true
                    ,
                    
                        key: false,
                        Name: 'Subject',
                        index: 'Subject',
                        editable: true,
                        edittype: 'select',
                        editoptions: 
                            value: 
                                '1': 'Maths',
                                '2': 'English',
                                '3': 'Physics'
                            
                        
                    ,
                    
                        key: false,
                        name: 'Marks',
                        align: "right",
                        index: 'Marks',
                        editable: true
                    
                ],
                pager: jQuery('#jqControlsSub'),
                height: '100%',
                rowNum: 20,
                sortname: 'StudentId',
                sortorder: 'asc',
                rowList: [10, 20, 30, 40, 50],
                viewrecords: true

            ).navGrid('#jqControlsSub', 
                edit: true,
                add: true,
                del: true,
                search: true,
                refresh: true
            , 
                zIndex: 100,
                url: '/Subjects/EditSub',
                closeOnEscape: true,
                closeAfterEdit: true,
                recreateForm: true,
                afterComplete: function(response) 
                    if (response.responseText) 
                        alert(response.responseText);
                        location.reload(true);
                    
                
            , 
                zIndex: 100,
                url: "/Subjects/CreateSub",
                closeOnEscape: true,
                closeAfterAdd: true,

                afterComplete: function(response) 
                    if (response.responseText) 
                        alert(response.responseText);
                        location.reload(true);
                    
                
            , 
                zIndex: 100,
                url: "/Subjects/DeleteSub",
                closeOnEscape: true,
                closeAfterDelete: true,
                recreateForm: true,
                msg: "Are you sure you want to delete ... ? ",
                afterComplete: function(response) 
                    if (response.responseText) 
                        alert(response.responseText);
                    
                
            );
        

    )

    function getDataSubGrid(pData, row_id) 
        gridId = "table_t";
        $.ajax(
            type: 'GET',
            url: "/Student/GetStudentsMarks?RowId=" + row_id,
            dataType: "json",
            success: function(data, textStatus) 
                console.log(data);
                ReceivedClientData(JSON.parse(getMain(data)).rows);
            ,
            error: function(data, textStatus) 
                alert('An error has occured retrieving data subgrid!');
            
        );
    

    function getMain(dObj) 
        if (dObj.hasOwnProperty('d'))
            return dObj.d;
        else
            return dObj;
    
);


[HttpPost]
public string CreateSub(Models.StudentSubjectInfo Model) 
    DataContext.SchoolContext db = new DataContext.SchoolContext();
    string msg;
    try 
        if (ModelState.IsValid) 
            db.StudentSubjectInfos.Add(Model);
            db.SaveChanges();
            msg = "Saved Successfully";
         else 
            msg = "Validation data not successfully";
        
     catch (Exception ex) 
        msg = "Error occured:" + ex.Message;
    
    return msg;



public string EditSub(Models.StudentSubjectInfo Model) 
    DataContext.SchoolContext db = new DataContext.SchoolContext();
    string msg;
    try 
        if (ModelState.IsValid) 
            db.Entry(Model).State = EntityState.Modified;
            db.SaveChanges();
            msg = "Saved Successfully";
         else 
            msg = "Validation data not successfully";
        
     catch (Exception ex) 
        msg = "Error occured:" + ex.Message;
    
    return msg;

[HttpPost]

public string DeleteSub(int id) 
    try 
        if (id != 0) 
            using(DataContext.SchoolContext db = new DataContext.SchoolContext()) 
                Models.StudentSubjectInfo studentCourseInfo = db.StudentSubjectInfos.Find(id);
                db.StudentSubjectInfos.Remove(studentCourseInfo);
                db.SaveChanges();
                return "Deleted successfully";
            
         else 
            return "Validation data not successfully";
        
     catch (Exception ex) 
        return "Error occured:" + ex.Message;
    


public JsonResult GetStudentsMarks(string sidx, string sort, int page, int rows, int RowId) 
    DataContext.SchoolContext db = new DataContext.SchoolContext();
    sort = (sort == null) ? "" : sort;
    int pageIndex = Convert.ToInt32(page) - 1;
    int pageSize = rows;

    var StudentMarksList = db.StudentSubjectInfos.Where(x => x.StudentsId.StudentId == RowId).Select(
        t => new 
            Id = t.SubjectId,
                t.StudentsId.StudentId,
                SubjectId = t.Id,
                Subject = t.SubjectId.Name,
                t.Marks
        );

    int totalRecords = StudentMarksList.Count();
    var totalPages = (int) Math.Ceiling((float) totalRecords / (float) rows);
    if (sort.ToUpper() == "DESC") 
        StudentMarksList = StudentMarksList.OrderByDescending(t => t.Marks);
        StudentMarksList = StudentMarksList.Skip(pageIndex * pageSize).Take(pageSize);
     else 
        //StudentMarksList = StudentMarksList.OrderBy(t => t.StudentId);
        //StudentMarksList = StudentMarksList.Skip(pageIndex * pageSize).Take(pageSize);
    
    var jsonData = new 
        total = totalPages,
            page,
            records = totalRecords,
            rows = StudentMarksList
    ;
    return Json(jsonData, JsonRequestBehavior.AllowGet);

想在Here is the table / grid i want to add info abot the student in the main grid and want to perform the crud in the subgrid as well for their marks 中执行 crud 如何使用 GetStudentsMarks 函数绑定子网格中的数据? 如何在jquery subgrid中使用ajax调用并解析数据并将其绑定到subgrid 提前致谢

【问题讨论】:

【参考方案1】:

-- JS部分

 $("#jqGrid").jqGrid(
    url: "/Student/GetStudents",
    datatype: 'json',
    mtype: 'Get',
    colNames: ['StudentId', 'FirstName', 'LastName', 'Gender', 'Class'],
    colModel: [
         key: true, hidden: true, name: 'StudentId', index: 'StudentId', editable: true ,
         key: false, name: 'FirstName', index: 'FirstName', editable: true ,
         key: false, name: 'LastName', index: 'LastName', editable: true ,
         key: false, name: 'Gender', index: 'Gender', editable: true, edittype: 'select', editoptions:  value:  'M': 'Male', 'F': 'Female', 'N': 'None'   ,
         key: false, name: 'Class', index: 'Class', editable: true, edittype: 'select', editoptions:  value:  '1': '1st Class', '2': '2nd Class', '3': '3rd Class', '4': '4th Class', '5': '5th Class'   
        // key: false, hidden: true, name: 'Name', align: "right", index: 'Name', editable: true ,
        // key: false, hidden: true, name: 'Marks', align: "right", index: 'Marks', editable: true 
    ],
    pager: jQuery('#jqControls'),
    rowNum: 10,
    sortname: 'StudentId',
    sortorder: 'asc',
    rowList: [10, 20, 30, 40, 50],
    height: '100%',
    viewrecords: true,
    subGrid: true,   
    iconSet: "fontAwesome",
    multiSort: true,
    sortable: true,
    loadonce: true,
    additionalProperties: ['Class', 'ClassLang'],
    autoencode: true,
    cmTemplate: 
        autoResizable: true
    ,
    autoresizeOnLoad: true,
    autowidth: true,
    autoResizing: 
        //resetWidthOrg: true,
        compact: true
    ,
    caption: 'Students Records',
    emptyrecords: 'No Students Records are Available to Display',
    jsonReader: 
        root: "rows",
        page: "page",
        total: "total",
        records: "records",
        repeatitems: false,
        Id: "0"
    ,
    multiselect: false,
    subGridRowExpanded: function (subgrid_id, row_id) 
        // we pass two parameters
        // subgrid_id is a id of the div tag created within a table
        // the row_id is the id of the row
        // If we want to pass additional parameters to the url we can use
        // the method getRowData(row_id) - which returns associative array in type name-value
        // here we can easy construct the following
        var subgrid_table_id;
        subgrid_table_id = subgrid_id + "_t";
        jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
        jQuery("#" + subgrid_table_id).jqGrid(
            url: "/Student/GetStudentsMarks?row_id=" + row_id,
            datatype: "json",
            colNames: ['Id','name','SubjectId' ,'Subject', 'Marks'],
            colModel: [
                 key: true, hidden: true, name: 'Id', index: 'Id', editable: false ,
                 key: true, hidden: true, name: 'StudentsId', index: 'StudentsId', editable: false ,
                 key: false, name: 'SubjectId', align: "center", index: 'SubjectId', editable: true, edittype: 'select', editoptions:  value:  1: 'Maths', 2: 'English', 3: 'Physics'   ,
                 key: false, name: 'Name', align: "center", index: 'Name', editable: false ,
                 key: false, name: 'Marks', align: "center", index: 'Marks', editable: true 
            ],
            pager: jQuery('#jqControlsSub'),
            height: '100%',
            rowNum: 20,
            sortname: 'StudentId',
            sortorder: 'asc',
            rowList: [10, 20, 30, 40, 50],
            viewrecords: true,
            subGrid: false,
            iconSet: "fontAwesome",
            multiSort: true,
            sortable: true,
            loadonce: true,
            additionalProperties: ['Name', 'Name'],
            autoencode: true,
            cmTemplate: 
                autoResizable: true
            ,
            autoresizeOnLoad: true,
            caption: 'Subject Records',
            emptyrecords: 'No Subject Records are Available to Display',
            jsonReader: 
                root: "rows",
                page: "page",
                total: "total",
                records: "records",
                repeatitems: false,
                Id: "0"
            
        ).navGrid('#jqControlsSub',  edit: true, add: true, del: true, search: true, refresh: true ,
            
                zIndex: 100,
                url: '/Subjects/EditSub?Student_Id=' + row_id + "",
                closeOnEscape: true,
                closeAfterEdit: true,
                recreateForm: true,
                afterComplete: function (response) 
                    if (response.responseText) 
                        alert(response.responseText);
                        location.reload(true);
                    
                
            ,
            
                zIndex: 100,
                url: "/Subjects/CreateSub?Student_Id=" + row_id + "",
                closeOnEscape: true,
                closeAfterAdd: true,
                afterComplete: function (response) 
                    if (response.responseText) 
                        alert(response.responseText);
                        location.reload(true);
                    
                
            ,
            
                zIndex: 100,
                url: "/Subjects/DeleteSub",
                closeOnEscape: true,
                closeAfterDelete: true,
                recreateForm: true,
                msg: "Are you sure you want to delete ... ? ",
                afterComplete: function (response) 
                    if (response.responseText) 
                        alert(response.responseText);
                    
                
            );
    
    //subGridRowExpanded: function (subgridDivId, rowId) 
    //    var subgridTableId = subgridDivId + "_t";
    //    $("#" + subgridDivId).html("<table id='" + subgridTableId + "'></table>");
    //    $("#" + subgridTableId).jqGrid(
    //        datatype: 'local',
    //        data: mySubgrids[rowId],
    //        colNames: ['Col 1', 'Col 2', 'Col 3'],
    //        colModel: [
    //             name: 'c1', width: 100 ,
    //             name: 'c2', width: 100 ,
    //             name: 'c3', width: 100 
    //        ]

    //);
    //
).navGrid('#jqControls',  edit: true, add: true, del: true, search: true, refresh: true ,
    
        zIndex: 100,
        url: '/Student/Edit',
        closeOnEscape: true,
        closeAfterEdit: true,
        recreateForm: true,
        afterComplete: function (response) 
            if (response.responseText) 
                alert(response.responseText);
                location.reload(true);
            
        
    ,
    
        zIndex: 100,
        url: "/Student/Create",
        closeOnEscape: true,
        closeAfterAdd: true,
        afterComplete: function (response) 
            if (response.responseText) 
                alert(response.responseText);
                location.reload(true);
            
        
    ,
    
        zIndex: 100,
        url: "/Student/Delete",
        closeOnEscape: true,
        closeAfterDelete: true,
        recreateForm: true,
        msg: "Are you sure you want to delete Student... ? ",
        afterComplete: function (response) 
            if (response.responseText) 
                alert(response.responseText);
                location.reload(true);
            
        
    );

);

-- CS部分

public string CreateSub([Bind(Exclude = "Id")] Models.StudentSubjectInfo Model, int Student_Id)

    
        DataContext.SchoolContext db = new DataContext.SchoolContext();
        string msg;
        Model.StudentsId = Student_Id;
        var data = db.StudentSubjectInfos.Where(x => x.StudentsId == Model.StudentsId && x.SubjectId == Model.SubjectId).FirstOrDefault();
        try
        
            if (ModelState.IsValid)
            
                if (data != null) 
                    msg = "This subject is already exist choose another";
                
                else
                
                    db.StudentSubjectInfos.Add(Model);
                    db.SaveChanges();
                    msg = "Saved Successfully";
                
            
            else
            
                msg = "Validation data not successfully";
            
        
        catch (Exception ex)
        
            msg = "Error occured:" + ex.Message;
        
        return msg;
    


    public string EditSub(Models.StudentSubjectInfo Model,int Student_Id)
    
        DataContext.SchoolContext db = new DataContext.SchoolContext();
        string msg;
        Model.StudentsId = Student_Id;
        Model.Id = db.StudentSubjectInfos.SingleOrDefault(x => x.StudentsId == Model.StudentsId && x.SubjectId == Model.SubjectId).Id;
        try
        
            if (ModelState.IsValid)
            
                var data = db.StudentSubjectInfos.Where(x => x.Id == Model.Id).FirstOrDefault();
                data.Marks = Model.Marks;
                data.SubjectId = Model.SubjectId;
                db.SaveChanges();
                msg = "Updated Successfully";
            
            else
            
                msg = "Validation data not successfully";
            
        
        catch (Exception ex)
        
            msg = "Error occured:" + ex.Message;
        
        return msg;
    

    [HttpPost]
    public string DeleteSub(int Id)
    
        try
        
            if (Id != 0)
            
                using (DataContext.SchoolContext db = new DataContext.SchoolContext())
                
                    Models.StudentSubjectInfo studentCourseInfo = db.StudentSubjectInfos.Find(Id);
                    db.StudentSubjectInfos.Remove(studentCourseInfo);
                    db.SaveChanges();
                    return "Deleted successfully";
                
            
            else
            
                return "Validation data not successfully";
            
        
        catch (Exception ex)
        
            return "Error occured:" + ex.Message;
        

【讨论】:

感谢您对社区的贡献。这可能是一个正确的答案,但对您的代码提供额外的解释会很有用,以便开发人员能够理解您的推理。这对于可能不熟悉语法的新开发人员特别有用。此外,它可以帮助减少对后续问题的需求。您介意用更多详细信息更新您的评论吗?

以上是关于想对父网格和子网格分别进行 ech 的 crud 操作的主要内容,如果未能解决你的问题,请参考以下文章

csharp WPF数据网格CRUD

在Grid Row中查找Control

如何在反应中更新按钮单击ag网格中的行

具有层次结构的网格自定义命令正在调用 javascript 函数两次。

雷林鹏分享:jQuery EasyUI 应用 - 创建展开行明细编辑表单的 CRUD 应用

雷林鹏分享:jQuery EasyUI 应用 - 创建展开行明细编辑表单的 CRUD 应用