Click here to Skip to main content
15,886,632 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Re-usability of View in MVC

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Apr 2015CPOL 9.5K   5  
Re-usability of view in MVC

Introduction

While working, I had an issue with the code repeating and development time so I have come up with the following idea. I just shared it here with the assumption that this may help you to fix the same issue.

The key point of this post is re-usability of the view. To explain it, the Create and Edit page of the Employee has been used. This will be possible only when the both UIs are similar, and really helpful when the UI is critical. The general scenario will be as follows:

Image 1

The scenario where same view is used will be as follows:

Image 2

Background

  1. MVC
  2. Entity Framework
  3. AngularJS

Initially, the ViewBag variable will be declared and the data will be stored in it accordingly as of whether it is create or edit ActionResult in Employee Controller. But, both of the Action results are returning the same view (Employee.cshtml).

EmployeeController.cs

ActionResults for create

C#
public ActionResult Create() 
        { 
//here viewbag variable is ViewBag.Employee  and the data stored inside is Create Employee 
 
            ViewBag.Employee = "Create Employee"; 
            return View("Employee"); 
        } 
public ActionResult Create([Bind(Include = "Id,Name,Position,NID")] Employee 
.Contracts.Employee employee) 
                private EmployeeDbContext db = new EmployeeDbContext (); 
                db.Employee.Add(employee); 
                db.SaveChanges(); 
//here viewbag variable is ViewBag.Employee  and the data stored inside is Create Employee 
 
                ViewBag.Employee = "Create Employee"; 
                return View("Employee",employee); 
        } 

ActionResults for Edit

C#
 public ActionResult Edit(int? id) 
        { 
          Employee.Contracts.Employee employee = db.Employee.Find(id); 
            if (employee == null) 
            { 
                return HttpNotFound(); 
            } 
//here viewbag variable is same as create( ViewBag.Employee ) 
//and the data stored inside is Edit Employee 
 
            ViewBag.Employee = "Edit Employee"; 
            return View("Employee",employee); 
        } 
 
        public ActionResult Edit([Bind(Include = "Id,Name,Position,NID")]  
        	Employee .Contracts.Employee employee) 
        { 
            if (ModelState.IsValid) 
            { 
                private EmployeeDbContext db = new EmployeeDbContext (); 
                db.Entry(employee).State = EntityState.Modified; 
                db.SaveChanges(); 
            } 
//here viewbag variable is same as create( ViewBag.Employee ) 
//and the data stored inside is Edit Employee 
 
            ViewBag.Employee = "Edit Employee"; 
            return View("Employee",employee); 
        } 

Employee.cshtml

HTML
@model Employee.Contracts.Employee 
@{ 
//here the viewbag.title will be shown according to the action result which is belongs to the tab tittle 
    ViewBag.Title = @ViewBag.Employee; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
}

<div>
//here the hidden field has used to store the data from viewbag variable
    <input type="hidden" id="employee" value="@ViewBag.Employee" />
       
<div class="container" ng-app="employeeApp">
        <div ng-controller="employeeCtrl">
 
            <form name="employeeForm">
//here the heading will be shown according to the viewbag variable
                <h2> @ViewBag.Employee</h2>
                <table>
                    <tr>
                        <td>Name</td>
                        <td><input type="text" 
                        ng-model="viewDataEditEmployee.Name" name="Name" />  </td>
                    </tr>
                    <tr>
                        <td>Position</td>
                        <td><input type="text" 
                        ng-model="viewDataEditEmployee.Position" name="Position" />  </td>
 
                    </tr>
                    <tr>
                        <td>NID</td>
                        <td><input type="text" 
                        ng-model="viewDataEditEmployee.NID" name="NID" />  </td>
                    </tr>
                </table>
                <div>
                    <input type="submit" 
                    ng-click="save()" value="Save" />
                </div>
            </form>
        </div>
    </div>
</div> 

Employee.js

JavaScript
var employeeApp = angular.module('employeeApp', []);
 
employeeApp.run()

employeeApp.controller('employeeCtrl', function ($scope, employeeDataSvc) {
//here the data stored in hidden field get access and 
//If it is Edit page it will fill the details of the employee in the relevant field
    if ($('#employee').val()  == "Edit Employee") {
  $scope.viewDataEditEmployee= employeeDataSvc.getData('EditEmployeeViewData');
}
    $scope.save = function () {
        alert
        var promisePut = employeeDataSvc.PutEmployee
		($scope.viewDataEditEmployee.Id, $scope.viewDataEditEmployee);
 
        promisePut.then(function (pl) {
 
            $scope.Message = "Updated Successfully";
        }, function (err) {
            console.log("Err" + err);
        });
    }
});
 
employeeApp.factory('employeeDataSvc', function ($window, $http) {
    var service = {}
    service.getData = function (data) {
        if ($window[data] !== undefined)
            return $window[data];
        else
            return undefined;
    }
 
    service.PutEmployee = function (employeeId, employeeData) {
        var request = $http({
            method: "PUT",
            url: "/api/EmployeeApi/",
            data: employeeData
        });
        return request;
    }
    return service;
});

EmployeeApiController.cs

C#
public IHttpActionResult PutEmployee(Employee.Contracts.Employee employee)
        { 
          private EmployeeDbContext db = new EmployeeDbContext ();
//here Employee Id =0 means It is new record to add to the db. else it is get updated.
           if(employee.Id==0)
          { 
            db.Employee.Add(employee);
           }
          else
          {
            db.Employee.FirstOrDefault(i => i.Id == employee.Id).Name =employee.Name;
           db.Employee.FirstOrDefault(i => i.Id == employee.Id).Position =employee.Position;
           db.Employee.FirstOrDefault(i => i.Id == employee.Id).NID=employee.NID;
          }
                    db.SaveChanges();  
        }

License

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


Written By
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --