1

View page:

jQuery("#theGrid").jqGrid({
    url: '/Student/Grid',
    datatype: "json",
    colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'],
    colModel: [
    { key: true, name: 'Id', sortable: true, resize: true, align: "center", hidden: true },
    { key: false, name: 'FirstName', index: 'FirstName', editable: true, align: "center", editrules: { required: true } },
    { key: false, name: 'MiddleName', index: 'MiddleName', editable: true, align: "center", editrules: { required: true } },
    { key: false, name: 'LastName', index: 'LastName', editable: true, align: "center", editrules: { required: true } },
    { key: false, name: 'Birthdate', index: 'Birthdate', editable: true, align: "center", editrules: { required: true }, formatter: 'date', editoptions: { dataInit: function (el) { setTimeout(function () { $(el).datepicker(); }, 200); } } },
    { key: false, name: 'Birthplace', index: 'Birthplace', editable: true, align: "center", editrules: { required: true } },
     { key: false, name: 'State', index: 'State', editable: true, align: "center", edittype: "select", editoptions: { value: "GJ:Gujarat;MH:Maharashtra;DL:Delhi;BNG:Banglore;RJ:Rajasthan" }, editrules: { required: true } },
      { key: false, name: 'Nationality', index: 'Nationality', editable: true, align: "center", editrules: { required: true } },
       { key: false, name: 'Religion', index: 'Religion', editable: true, align: "center", editrules: { required: true } },
        {
            key: false, name: 'IsHandicaped', index: 'IsHandicaped', editable: true, align: "center", edittype: "checkbox", editoptions: { value: "True:False" }
        },
    {
        key: false,
        name: 'Actions',
        index: 'tax',
        width: 80,
        align: "center",
        formatter: 'actions',
        formatoptions: {
            keys: true,
           delOptions: { url: '/Student/Delete' }
        }
    }
    ],
    rowNum: 10,
    rownumbers: true,
    autowidth: true,
    rowList: [5, 10, 20],
    pager: '#gridPager',
    sortname: 'invdate',
    viewrecords: true,
    sortorder: "acc",
    altRows: true,
    delicon: 'glyphicon glyphicon-trash',
    altclass: 'table table-striped',
    jsonReader: {
        repeatitems: false
    },
    editurl: '/Student/Edit',
    mtype:"PUT",
    height: '100%',
    hiddengrid: false






});
jQuery("#theGrid").jqGrid('navGrid', '#gridPager', { "edit": false, "add": false, "del": false, "search": false, view: false });


$("#theGrid").jqGrid('inlineNav', '#gridPager',
{
    add: true,
    addicon: "ui-icon-plus",
    save: true,
    saveicon: "ui-icon-disk",
    cancel: true,
    cancelicon: "ui-icon-cancel",
    "refresh": true,
    "view": true,
    addoptions: {
        url: '/Student/Create'
    },

    addParams: {

         addRowParams: {
             url: '/Student/Create',
             mtype:"POST",
             keys: true,
             oneditfunc: function (rowid) {
                 alert("new row with rowid=" + rowid + " are added.");

             }
         },

        afterSubmit: function (response, postdata) {
    if (response.responseText == "") {
        $(this).jqGrid('setGridParam',
        { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
        return [true, ''];
    } else {
        $(this).jqGrid('setGridParam',
        { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
        return [false, response.responseText];
    }
}
     }


 });

Controller:

  public JsonResult Grid(string sidx, string sord, int page, int rows)
    {
        int pageIndex = Convert.ToInt32(page) - 1;
        int pageSize = rows;
        IEnumerable<Student> StudentData = db.Students.ToList();
        int totalRecords = StudentData.Count();
        var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
        if (sord.ToUpper() == "DESC")
        {
            StudentData = StudentData.OrderByDescending(s => s.Id);
            StudentData = StudentData.Skip(pageIndex * pageSize).Take(pageSize);
        }
        else
        {
            StudentData = StudentData.OrderBy(s => s.Id);
            StudentData = StudentData.Skip(pageIndex * pageSize).Take(pageSize);
        }
        var jsonData = new
        {
            total = totalPages,
            page,
            records = totalRecords,
            rows = StudentData
        };
        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
    public string Create([Bind(Exclude = "Id")] Student student)
    {
        string msg;
        try
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                msg = "Saved Successfully";
            }
            else
            {
                msg = "Validation data not successfull";
            }
        }
        catch (Exception ex)
        {
            msg = "Error occured:" + ex.Message;
        }
        return msg;
    }
    public string Edit(Student student)
      {
        string msg;
        try
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                msg = "Saved Successfully";
            }
            else
            {
                msg = "Validation data not successfull";
            }
        }
        catch (Exception ex)
        {
            msg = "Error occured:" + ex.Message;
        }
        return msg;
    }


    //Deletes the product
    public string Delete(int Id)
    {
        Student student = db.Students.Find(Id);
        db.Students.Remove(student);
        db.SaveChanges();
        return "Deleted successfully";
    }

When i add new row inline and click on save ,everytime it calls edit method of controller. Can anybody tell me how can i trigger create method of controller to insert new record in database.Thanks in advance.

How to call this create method of controller for insert new row in database?

  • You should write always **which fork of jqGrid you use and in which version**. Which version of ASP.NET MVC you use? Moreover I strictly recommend you to post simple code instead of posting your current code. The `colModel` which you post have 11 columns. Is all the columns are related to the question? Could one reduce all to for example `Id`, `FirstName`, `LastName` and `Actions`? Are `[ValidateAntiForgeryToken]` and `[Bind(Exclude = "Id")]` attributes really required in `Create`? **What is your current main problem?** Will be `Create` called? Will be `student` data be filled? – Oleg Oct 13 '15 at 08:12
  • You use `afterSubmit` callback of `addParams`. Where you get that `addRow` support such callback. See [addRow](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing#addrow) documentation. The calback exist in **form editing** and not in inline editing. You test inside of `afterSubmit` callback for `response.responseText == ""`, but the server (`Create` action) returns always non-empty string. What is your goal? What you try to implement? If you have some question, then please describe it clear. – Oleg Oct 13 '15 at 08:18
  • can you explain me by writing code snippet please ? I am using JqGrid 4.4.4 For Edit/Delete i used formatter:"actions" and it semms to be working fine. But now iam implementing inline add row in grid as well as in database. – Sagar Mistry Oct 13 '15 at 08:57
  • Sorry, but writing snippet for you is too many work. If `Edit` action will be called than you can add `oper` parameter to it (`Edit(string oper, Student student)`) and remove `url: '/Student/Create'`. You will be see that `Edit` action will be called and `oper` will be `"add"`, `"edit"` or `"del"` (the last if you would share `editurl` to Delete too). The usage of old 4.4.4 is not recommended. If you installed it from NuGet by usage old `jQuery.jqGrid` package then you should uninstall it and install `free-jqGrid` package instead. – Oleg Oct 13 '15 at 09:10
  • Exactly, I am having this problem with old version only,But it project requirement. – Sagar Mistry Oct 13 '15 at 09:22
  • Do you tried to add `string oper`? What is your project requirement exactly? – Oleg Oct 13 '15 at 09:24
  • See, I want to one record of Student into database with inline row add in jqGrid.and, Edit / delete working fine with formatter:actions. But for adding nerw record into grid and posting it to the server (database) is my exact goal. But i am new to JqGrid and i dont know how to acheive it. – Sagar Mistry Oct 13 '15 at 09:29
  • I suggested you to remove `url: '/Student/Create'` option and to add `string oper` parameter to `Edit` action which seems be called (isn't so). If you remove `url: '/Student/Create'` then jqGrid will use `editurl` for posting the data. Inside of `Edit` action you can test the value of `oper` parameter and do the corresponding action. – Oleg Oct 13 '15 at 09:33
  • when i click one plus icon in navbar of grid, new inline row comes before first row,but when i submit the data everytime it triggers the Url of Edit method – Sagar Mistry Oct 13 '15 at 09:33
  • Where you see a problem with calling of `Edit` method if you have additional parameter `oper` which have **different value** for Add and Edit actions? What is your goal: creating a working solution or creating nice looking solution? If you need to create nice looking solution then you should rewrite all your code and invest many time in studying of jqGrid. So I suggested you **pragmatic** solution with usage of one `Edit(string oper, Student student)` instead of `Edit(Student student)` and `Create`. – Oleg Oct 13 '15 at 09:38
  • Okay , But how can i specify oper value for add and edit operation? – Sagar Mistry Oct 13 '15 at 09:40
  • You don't understand me. **jqGrid initialize some properties for you automatically**. You don't need to do anything. You need just use the parameters which one send to you. Moreover I wrote multiple time: try to add `string oper` and I asked you "Do you tried to add string oper?". Did you tried it? If you just added `string oper` and set breakpoint inside of `Edit` you will see that `oper` is already filled. Why spend my time and your time in long discussion? Just do and see the results. – Oleg Oct 13 '15 at 09:44
  • Yes i tried it that way but in both operation, value of oper comes "edit" – Sagar Mistry Oct 13 '15 at 09:57
  • You use **retro version of jqGrid**. If the user save the row by pressing Enter key the `oper` should be correct, but click on "Save" button uses wrong options. It's old bug fixed since years. Try to replace URLs (all, inclusive css) to jqGrid (at least temporary) to URLs of free jqGrid 4.9.2 described [here](https://github.com/free-jqgrid/jqGrid/wiki/Access-free-jqGrid-from-different-CDNs). Additionally I recommend you to add `id: "Id"` property to `jsonReader`. After that you can remove unneeded hidden `"Id"` column: rowids (`id` attribute of ``) will be get from `"Id"`. – Oleg Oct 13 '15 at 10:05
  • I understood your suggestion.Thank for your time and help. :) – Sagar Mistry Oct 13 '15 at 10:17

0 Answers0