Click here to Skip to main content
15,888,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following controller action method.


public int BulkUpdate(List<Employee> employees)
         {

           Connection();
           employees = GetAllEmployees().ToList();
            // using reflection, i mean why did i use this ??
            //used it for converting the generic list into datatables.
           DataTable dt = new DataTable(typeof(Employee).Name);
           PropertyInfo[] props = typeof(Employee).GetProperties(BindingFlags.Public | BindingFlags.Instance);
           foreach (var prop in props)
           {
               dt.Columns.Add(prop.Name);
           }

           foreach (var employee in employees)
           {
               var values = new object[props.Length];
               for (int i = 0; i < props.Length; i++)
               {
                   values[i] = props[i].GetValue(employee, null);
               }

               dt.Rows.Add(values);
           }
           //
           using (SqlCommand cmd = new SqlCommand("BulkUpdateEmployee", con))
           {
               cmd.CommandType = CommandType.StoredProcedure;
               SqlParameter parameter = cmd.Parameters.AddWithValue("@tblEmployeeType", dt);
               parameter.SqlDbType = SqlDbType.Structured;
               parameter.TypeName = "dbo.EmployeeType";


               con.Open();
               var rowsAffected = cmd.ExecuteNonQuery();
               con.Close();

               return rowsAffected;
           }//using ends here

       }



and this method is being called in main controller:


[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
       public JsonResult BulkUpdateOrInsert(List<Employee> employees)
       {
           int rowsAffected=empRepo.BulkUpdate(employees);
           return Json(rowsAffected, JsonRequestBehavior.AllowGet);

       }



and this is the View file :


@using System.Collections
@model IEnumerable<Employee_Management_System.Models.Employee>

@{
    ViewBag.Title = "BulkUpdateOrInsert";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">
    $("body").on("click", "#btnSave", function() {
            //Have to Loop through the Table rows and build a JSON array maybe try passing it to Controller action.
        var employees = new Array();
            debugger;
            $("#tblEmployees tbody tr").each(function() {
                var row = $(this);
                var employee = {};
            employee.Name = row.find("td").eq(0).html();
            employee.City = row.find("td").eq(1).html();
            employee.Department = row.find("td").eq(2).html();
            employee.Gender = row.find("td").eq(3).html();
            employees.push(employee);
        });
    </script>
    @*end of section script*@

    <script type="text/javascript">
                $.ajax({
                    type: "POST",
                url: "/Employee/BulkUpdateOrInsert",
                data: JSON.stringify(employees),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                    success: function(r) {
                    alert(r + " record(s) inserted.");
            }
});
    </script>
</head>
<body>
    <h2>BulkUpdateOrInsert</h2>


    @using (Html.BeginForm("BulkUpdateOrInsert", "Employee", "POST"))
    {
        @Html.AntiForgeryToken()


        <h4>Employee</h4>
        <hr />

        <table class="table" id="tblEmployees">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Name)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.City)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Department)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Gender)
                    </th>
                    <th></th>
                </tr>
            </thead>

            @foreach (var item in Model)
            {
                <tbody>
                <tr>
                    <td>@Html.HiddenFor(modelItem => item.EmployeeId)</td>
                    <td>
                        @Html.EditorFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.City)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.Department)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.Gender)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new {id = item.EmployeeId}) |
                        @Html.ActionLink("Details", "Details", new {id = item.EmployeeId}) |
                        @Html.ActionLink("Delete", "Delete", new {id = item.EmployeeId})
                    </td>
                </tr>
                </tbody>
            }

        </table>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" id="btnSave" value="Save All" class="btn btn-default" />
            </div>
        </div>
        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
        @section Scripts {
            @Scripts.Render("~/bundles/jqueryval")
        }
    }
</body>

</html>


The problem is that the view is not loaded for Updating the records.
My requirement is to load the view with pre existing data in database.
Edit the records,return the Generic List of Updated Records --> Convert them to Datatable,and pass that datatable to stored procedure.(this i have done).The problem is i am not able to load the view to update entries in database.

What I have tried:

I have no idea at all how to approach the issue.
Posted
Updated 5-Dec-19 23:43pm

1 solution

Do not mix Get and Post/Put method.
Write a jQuery $(document).ready() method to load all your records from db with Get method.
On Post you can send all records and Save or Update them, for that you can call Post/Put method
 
Share this answer
 
Comments
chaturvedi_anshumaan_20191 6-Dec-19 6:55am    
Do you mean something like this?

$(document).ready(function () {
$('#tblEmployees').ready({
$.ajax{
type: "POST",
url: "/Employee/Index",
data: JSON.stringify(employees),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
chaturvedi_anshumaan_20191 6-Dec-19 6:57am    
what i have written is wrong i think.
Mehul M Thakkar 6-Dec-19 7:01am    
it is post call, if you want to get the employees just call get method
Richard Deeming 6-Dec-19 9:04am    
NB: Have a look at the jQuery documentation[^] - $(document).ready(function(){ ... }) is deprecated in favour of $(function(){ ... }):

"jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

* $( handler )
* $( document ).ready( handler )
* $( "document" ).ready( handler )
* $( "img" ).ready( handler )
* $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated."

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900