Part 28 - Customizing the autogenerated create view

In this video we will discuss, customizing the auto-generated create view. (接part27)

At the moment, none of the fields on "Create" view are required. This means,when you click on the "Create" button without filling any data, NULL values are stored in all the columns of tblEmployee 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 loose the changes if the class is auto-generated again. 

To achieve this, add a class file with "name=Employee.cs" to "Models" folder.

Copy and paste the following code in "Employee.cs" file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MVCDemo.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]
        [Display(Name="Department")]
        public int DepartmentId { get; set; }
    }
}

At this point, run the application and click on the "Create" button without filling any data. Notice that we get validation error messages as expected. In a later video session, we will discuss changing the colour of the validation messages.

If you want "Select Department" as the first item in the "Department" dropdownlist on"Create" view, then, 
REPLACE THE FOLLOWING LINE
@Html.DropDownList("DepartmentId"String.Empty)

WITH
@Html.DropDownList("DepartmentId""Select Department")

Notice that, a textbox is used for gender. It is ideal 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)

WITH
@Html.DropDownList("Gender"new List<SelectListItem>
{
new SelectListItem { Text = "Male", Value="Male" },
new SelectListItem { Text = "Female", Value="Female" }
}, "Select Gender") 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值