Using jQuery for displaying ASP.NET MVC Partial View to Perform Edit Operation

ASP.NET MVC replaces the traditional WebForm eventing model with a more maintainable Model View Controller approach towards building web pages. Without events and controls, requirements for partial page updates are met by using jQuery scripting and via Partial Views.

Also read - ASP.NET MVC: Displaying Partial Views using jQuery UI Dialog Boxes

Recently while conducting an MVC training, one of my participants put forth a query. His requirement was that in the Index view, the Edit View must be displayed when an end-user selects a record from the Index List. This got us all thinking and here’s the solution.

For this article, Visual Studio 2012 RC is used and for the model layer SQL Server 2012 is used with database as Company. However you can use VS 2010 and SQL 2008 also. For model designing, ADO.NET EF is used. The design of ADO.NET for the EmployeeInfo table is as shown below:

I1_EF

Step1: In the MVC project, add a new ‘EmployeeInfo’ controller and add the constructor and the implementation for Index and Edit Action methods as below:

CompanyEntities objContext;
public EmployeeInfoController()
{
    objContext = new CompanyEntities();
}
public ActionResult Index()
{
    var Employees = objContext.EmployeeInfoes.ToList();
    return View(Employees);
}

public ActionResult Edit(int id)
{
    var Employee = objContext.EmployeeInfoes
                        .Where(eno => eno.EmpNo == id).First();
    return PartialView("EditEmployeeDetails", Employee);
}

//
// POST: /EmployeeInfo/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        var Employee = objContext.EmployeeInfoes
                        .Where(eno => eno.EmpNo == id).First();
        Employee.EmpName = collection[1].ToString();
        Employee.Salary = Convert.ToDecimal(collection[2]);
        Employee.DeptName = collection[3].ToString();
        Employee.Designation = collection[4].ToString();
        objContext.SaveChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

Note : The Edit method with ‘id’ as parameter returns the partial view of name ‘EditEmployeeDetails’ which will be added in the next task.

Step 2: Add a strongly typed Index view and a strongly typed partial view of name ‘EditEmployeeDetails.cshtml’ in the project. The model class set for both these views is EmployeeInfo which is made available to the MVC project in Model folder using ADO.NET EF.

Step 3: Open Index.cshtml in the ‘EmployeeInfo’ sub-folder of the Views folder and add the jquery reference as shown below:

<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")"
type="text/javascript"></script>

Step 4: Add the following css in Index.cshtml. This css will be used for providing selection effects to the end user:

<style>
.background {
background-color:Red;
font-weight:700;
}
</style>

Step 5: Design the Html for Index.cshtml as below:

<table>
<tr>
    <td>
        <table id="tlbEmpinfo">
        <tr>
             <th>
                EmpNo
            </th>
            <th>
                EmpName
            </th>
            <th>
                Salary
            </th>
            <th>
                DeptName
            </th>
            <th>
                Designation
            </th>
        </tr>

        @foreach (var item in Model) {
        <tr>
               <td>
                @Html.DisplayFor(modelItem => item.EmpNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmpName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Salary)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.DeptName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Designation)
            </td>
        </tr>
        }

        </table>
    </td>
    <td>
        <div id="employeeinfo" title="Employee No" 
            style="background-color:Yellow; border-bottom-width:thin">
        </div>
    </td>
</tr>

</table>

Step 6: Write the below jQuery for the Table row selection:

<script type="text/javascript">
    $(document).ready(function () {
        //S1: Get the Table row <tr>
        var tr = $('#tlbEmpinfo').find('tr');
        //S2: Bind 'click' event for the <tr>
        tr.bind('click', function (e) {
            //S3: Add the css class
            $(this).addClass('background');
            //S4: Read the Value for the zero-th index cell in the clicked <tr>
            var EmpNo = $(this).closest('tr').children('td:eq(0)').text();
            //S5: Make an ajax call for Edit Action from the Controller.
            $.ajax({
                type: "GET",
                url: "/EmployeeInfo/Edit/" + EmpNo,
                 dataType:"html",
                 success: function (evt) {
                    $('#employeeinfo').html(evt);
                },
                error: function (req, status, error) {
                    alert("Error!Occured");
                }
            });

           
        });
        tr.bind('mouseleave', function (e) {
            $(this).removeClass('background');
        });
    });
</script>

Please read comments applied on jQuery.

Step 7: Run the application and navigate to the EmployeeInfo Index action, the result will be as shown below:

I2_Res_1

Click on any Table row, its background color will be changed to read and partial view with selected Employee will be displayed as below:

 

I3_Res_2

The above image shows that when the Row with EmpNo as 155 is clicked, the Partial View is added on the Index View at runtime using jQuery and shows the selected employee details. Now end-user can edit the Employee details and click on save to post values back to server.

Conclusion:

Using jQuery in an MVC Application, developers can provide a dnyamic, ajaxified user experience. As shown in the example we can build UI that renders only updated parts of a page by using partial postback.

The entire source code of this article can be downloaded over here OR Fork the code on GitHub.






About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

3 comments:

Andy said...

Nice work Mahesh :) - just what I was after.

btw I've noticed that an error is thrown when clicking the header row, which obviously doesn;t include a real row ID.

This can be fixed if you split the table into thead and tbody sections, and then amend the selector to:

var tr = $('#tlbEmpinfo').find('tbody>tr');

Anonymous said...

Yes, That true. I have also noticed that.
I will rectify it.
Thanks a lot.
Mahesh Sabnis

Unknown said...

very informative post indeed.. being enrolled in http://www.wiziq.com/course/57-fresher-training-projects was looking for such articles online to assist me.. and your post helped me a lot