Customizing Auto Generated Index and Create Views

Customizing Auto-Generated Index and Create View

In this article, I am going to discuss customizing the auto-generated index and create view in ASP.NET MVC application. Please read our previous article before proceeding to this article as this article is a continuation part of our previous article. In our previous article, we discussed the step by step procedure to perform CRUD operations using Entity Framework in ASP.NET MVC Application.

Customizing Index View:

Run the application and navigate to the index view which should display the data as shown below.

Customizing Auto Generated Index View in ASP.NET MVC Application

As shown in the above “Index” view, it is using “Name” as the column header for both employee and department name. This is because the “Name” column is used in both the database tables (Employee and Department) and the entity framework used these column names to generate the “Name” property in both 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; }
    }
}

Here, we need to change the department column header to “Department Name” instead of just “Name“.  In order to do this add a class file with the name PDepartment.cs within the “Models” folder. Once you created the PDepartment.cs class file then simply copy and paste the following code in it.

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 the above changes in place, run the application and notice the column name is displayed as Department Name. This is achieved by using the “Display” attribute that is present in the “System.ComponentModel.DataAnnotations” namespace.

If you are wondering why can’t we apply the “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. 

Customizing the auto-generated create view.

At the moment none of the fields on the “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 the Employee table.

How to make these fields on the “Create” view required?

Add [Required] attribute to the properties of 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 the name PEmployee.cs within the “Models” folder. Once you created the PEmployee.cs class file, then simply copy and paste the following code in it.

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 as shown in the below image.

Customizing Auto Generated Create View in ASP.NET MVC Application

If you want “Select Department” as the first item in the “Department” dropdownlist on “Create” view then Replace the following code in the Create.cshtml view.

@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 drop down list for gender rather than a textbox. To achieve this make the following changes to the “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 am going to discuss how to customize the auto-generated Edit view in ASP.NET MVC application. Here, in this article, I try to explain customizing the auto-generated index and create views in ASP.NET MVC application. I hope this article will help you with your needs. 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 *