Customizing Auto Generated Index and Create Views

Customizing Auto Generated Index and Create View

In this article, we will discuss customizing auto generated index and create view in ASP.NET MVC application. Please read the previous article before proceeding to this article as we are going to use the same example that we started in our previous article

At the moment the “Index” view is using “Name” as the column header for both employee name and department name. This is because “Name” column is used in both the database tables (Employee & Department) and entity framework has used these column names to generate “Name” property in Employee and Department classes that are auto-generated as shown below.

Employee.cs File
namespace CRUD_Using_EF.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public Nullable<decimal> Salary { get; set; }
        public Nullable<int> DepartmentId { get; set; }
    
        public virtual Department Department { get; set; }
    }
}
Department.cs File
namespace CRUD_Using_EF.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Department
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Department()
        {
            this.Employees = new HashSet<Employee>();
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Employee> Employees { get; set; }
    }
}

I want to change the department column header to “Department Name” instead of just “Name”. To achieve this add a class file with “name=PDepartment.cs” to “Models” folder.

Copy and paste the following code in “PDepartment.cs” file

namespace CRUD_Using_EF.Models
{
    [MetadataType(typeof(DepartmentMetaData))]
    public partial class Department
    {
    }

    public class DepartmentMetaData
    {
        [Display(Name = "Department Name")]
        public string Name { get; set; }
    }
}

With these changes run the application and notice the column name is displayed as Department Name. This is achieved by using “Display” attribute that is present in “System.ComponentModel.DataAnnotations” namespace.

If you are wondering why can’t we apply “Display” attribute directly to the auto-generated “Department” class instead of creating another partial “Department” and DepartmentMetaData class. We can do it. There is nothing stopping us from doing it but every time the Department class is auto-generated our custom changes will be lost. This is the reason for creating another partial class and applying our changes. 

Now we will discuss customizing the auto-generated create view.

At the moment none of the fields on “Create” view are required. That means when we click on the “Create” button without filling out any data NULL values are stored in all the columns of Employee table.

So, how to make these fields on the “Create” view required?

Add [Required] attribute to the “Employee” class. The “Employee” class that is present in “EmployeeDataModel.Designer.cs” is auto-generated by the entity framework. There is no point in adding the [Required] attribute to this class as we will lose the changes if the class is auto-generated again. 

To achieve this add a class file with “name=PEmployee.cs” to “Models” folder.

Copy and paste the following code in “PEmployee.cs” file

using System.ComponentModel.DataAnnotations;
namespace CRUD_Using_EF.Models
{
    [MetadataType(typeof(EmployeeMetaData))]
    public partial class Employee
    {
    }

    public class EmployeeMetaData
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public string Gender { get; set; }

        [Required]
        public string City { get; set; }

        [Required]
        public string Salary { get; set; }

        [Required]
        public int DepartmentId { get; set; }
    }
}

At this point run the application and click on the “Create” button without filling out any data. Notice that we get validation error messages as expected.

If we want “Select Department” as the first item in the “Department” dropdownlist on “Create” view then

REPLACE THE FOLLOWING LINE

@Html.DropDownList(“DepartmentId”,null , htmlAttributes: new { @class = “form-control” })

with

@Html.DropDownList(“DepartmentId”,null , “Select Department”, htmlAttributes: new { @class = “form-control” })

Notice that a textbox is used for gender. It is an ideal situation to have a dropdownlist for gender rather than a textbox. To achieve this make the following changes to “Create.cshtml” view.

REPLACE THE FOLLOWING CODE

@Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = “form-control” } })
with
@Html.DropDownList(“Gender”, new List<SelectListItem>
{
new SelectListItem { Text = “Male”, Value=”Male” },
new SelectListItem { Text = “Female”, Value=”Female” }
}, “Select Gender”, new { @class = “form-control” }) 

Below is the complete code for Create.cshtml view

@model CRUD_Using_EF.Models.Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Gender", new List<SelectListItem>
{
new SelectListItem { Text = "Male", Value="Male" },
new SelectListItem { Text = "Female", Value="Female" }
}, "Select Gender", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DepartmentId, "DepartmentId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DepartmentId",null , "Select Department", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DepartmentId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

In the next article, I will discuss how to customize the auto-generated Edit view in ASP.NET MVC application.

SUMMARY
In this article, I try to explain customizing auto generated index and create view  in ASP.NET MVC application. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *