Hide WebGrid columns in Edit mode using jQuery in ASP.Net MVC

Last Reply one month ago By dharmendr

Posted one month ago

Hi,

I have a webgrid in ASP.NET MVC contains 3 columns ID, Name & LCL.

I want to hide ID column & Name column when the row is edit mode.

Help me to do it.

My code

webGrid.Column(header: "ID", format: @<span class="label2">@item.sID</span>, style: "sID"),
webGrid.Column(header: "Name", format: @<span class="label2">@item.Name</span>, style: "Name"),
webGrid.Column(header: "LCL", format: @<span>
    <span class="label2">@item.LCL</span>
    <input class="text" type="text" value="@item.LCL" style="display:none" /></span>, style: "LCL"),

 

            $("body").on("click", "#WebGrid TBODY .Edit", function () {
                var row = $(this).closest("tr");
                $("td", row).each(function () {
                    if ($(this).find(".text").length > 0) {
                        $(this).find(".text").show();
                        $(this).find(".label2").hide();
                    }
                });
                row.find(".Update").show();
                row.find(".Cancel").show();
                $(this).hide();
            });

 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi comunidadmexi,

Check the below example.

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        EmployeeEntities entities = new EmployeeEntities();
        List<Employee> employees = entities.Employees.Take(3).ToList();
        employees.Insert(0, new Employee());

        return View(employees.ToList());
    }

    [HttpPost]
    public JsonResult InsertEmployee(Employee employee)
    {
        using (EmployeeEntities entities = new EmployeeEntities())
        {
            entities.Employees.Add(employee);
            entities.SaveChanges();
        }

        return Json(employee);
    }

    [HttpPost]
    public ActionResult UpdateEmployee(Employee employee)
    {
        using (EmployeeEntities entities = new EmployeeEntities())
        {
            Employee updatedEmployee = (from c in entities.Employees
                                        where c.EmployeeID == employee.EmployeeID
                                        select c).FirstOrDefault();
            updatedEmployee.FirstName = employee.FirstName;
            updatedEmployee.BirthDate = employee.BirthDate;
            entities.SaveChanges();
        }

        return new EmptyResult();
    }
}

View

@model IEnumerable<Employee>

@{
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: false);
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @webGrid.GetHtml(
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns
        (
            webGrid.Column(header: "Id", format: @<span class="label">@item.EmployeeID</span>, style: "EmployeeId"),
            webGrid.Column(header: "Name", format: @<span>
                    <span class="label">@item.FirstName</span>
                    <input class="text" type="text" value="@item.FirstName" style="display:none" />
                </span>, style: "Name"),
            webGrid.Column(header: "DOB", format: @<span>
                    <span class="label">@Convert.ToDateTime(item.BirthDate).ToString("dd/MM/yyyy")</span>
                    <input class="text DOB" type="text" value="@Convert.ToDateTime(item.BirthDate).ToString("dd/MM/yyyy")" style="display:none" />
                </span>, style: "DOB"),
            webGrid.Column(header: "Time", format: @<span>
                    <span class="label">@Convert.ToDateTime(item.BirthDate).ToString("HH:mm")</span>
                    <input class="text Time" type="text" value="@Convert.ToDateTime(item.BirthDate).ToString("HH:mm")" style="display:none" onchange="return validateHoursMinutes(this)" />
                </span>, style: "Time"),
            webGrid.Column(format:@<span class="link">
                    <a class="Edit" href="javascript:;">Edit</a>
                    <a class="Update" href="javascript:;" style="display:none">Update</a>
                    <a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
                </span>)
        )
    )
    <br />
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td style="width: 150px">
                Name:<br />
                <input type="text" id="txtName" style="width:140px" />
            </td>
            <td style="width: 150px">
                Birth Date:<br />
                <input type="text" id="txtDOB" style="width:140px" />
            </td>
            <td style="width: 100px">
                <br />
                <input type="button" id="btnAdd" value="Add" />
            </td>
        </tr>
    </table>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <link rel="Stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
    <script type="text/javascript">
        jQuery(function ($) {
            var options = $.extend({},
                $.datepicker.regional["es"], {
                    dateFormat: "dd/mm/yy",
                    changeMonth: true,
                    changeYear: true,
                    yearRange: "-2:+0",
                    highlightWeek: true,
                    maxDate: 0
                });
            $(".DOB").datepicker(options);
        });
    </script>
    <script type="text/javascript">
        $(function () {
            var row = $("#WebGrid TBODY tr:eq(0)");
            if ($("#WebGrid TBODY tr").length > 1) {
                row.remove();
            } else {
                row.find(".label").html("");
                row.find(".text").val("");
                row.find(".link").hide();
            }
        });
        function AppendRow(row, employeeId, name, dob) {
            //Bind EmployeeId.
            $(".EmployeeId", row).find(".label").html(employeeId);

            //Bind Name.
            $(".Name", row).find(".label").html(name);
            $(".Name", row).find(".text").val(name);

            //Bind BirthDate.
            $(".DOB", row).find(".label").html(dob);
            $(".DOB", row).find(".text").val(dob);

            //Bind Time.
            $(".Time", row).find(".label").html(dob);
            $(".Time", row).find(".text").val(dob);

            row.find(".link").show();
            $("#WebGrid TBODY").append(row);
        };

        $("body").on("click", "#btnAdd", function () {
            var txtName = $("#txtName");
            var txtDOB = $("#txtDOB");

            var employee = {};
            employee.FirstName = txtName.val();
            employee.BirthDate = txtDOB.val();

            $.ajax({
                type: "POST",
                url: "/Home/InsertEmployee",
                data: '{employee:' + JSON.stringify(employee) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var row = $("#WebGrid TBODY tr:last-child").clone();
                    if (row.find(".label").is(":empty")) {
                        $("#WebGrid TBODY tr:last-child").remove();
                    }
                    AppendRow(row, r.EmployeeID, r.FirstName, r.BirthDate);
                    txtName.val("");
                    txtDOB.val("");
                }
            });
        });

        $("body").on("click", "#WebGrid TBODY .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find(".text").length > 0) {
                    $(this).find(".text").show();
                    $(this).find(".label").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            $(this).hide();
            // Hide 1st column.
            $('#WebGrid th:nth-child(1)').hide();
            $('#WebGrid td:nth-child(1)').hide();
        });

        $("body").on("click", "#WebGrid TBODY .Update", function () {
            var row = $(this).closest("tr");
            var employee = {};
            employee.EmployeeID = row.find(".EmployeeId").find(".label").html();
            employee.FirstName = row.find(".Name").find(".text").val();
            employee.BirthDate = row.find(".DOB").find(".text").val();

            if (employee.FirstName != '' && employee.BirthDate != '') {
                $("td", row).each(function () {
                    if ($(this).find(".text").length > 0) {
                        var span = $(this).find(".label");
                        var input = $(this).find(".text");
                        span.html(input.val());
                        span.show();
                        input.hide();
                    }
                });
                row.find(".Edit").show();
                row.find(".Cancel").hide();
                $(this).hide();
                $.ajax({
                    type: "POST",
                    url: "/Home/UpdateEmployee",
                    data: '{employee:' + JSON.stringify(employee) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                });
            }
            else {
                alert("Please fill the details.");
                return false;
            }

            // Show 1st column.
            $('#WebGrid th:nth-child(1)').show();
            $('#WebGrid td:nth-child(1)').show();
        });

        function validateHoursMinutes(ele) {
            var isValid;
            var regx = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])(:[0-5][0-9])?$/;
            if (regx.test(ele.value)) {
                isValid = true;
                ele.style.backgroundColor = '#bfa';
            } else {
                isValid = false;
                ele.style.backgroundColor = '#fba';
            }

            return isValid;
        }

        $("body").on("click", "#WebGrid TBODY .Cancel", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find(".text").length > 0) {
                    var span = $(this).find(".label");
                    var input = $(this).find(".text");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Update").hide();
            $(this).hide();
            // Show 1st column.
            $('#WebGrid th:nth-child(1)').show();
            $('#WebGrid td:nth-child(1)').show();
        });
    </script>
</body>
</html>