JumpStart # 33– Ignore a property of Model from EditorFor Scaffolding in ASP.Net MVC

In this JumpStart, I am going to show on how to prevent automatic scaffolding of a Model Property while using @Html.EditorFor extension in ASP.Net MVC.

Many times we might create a Model (what I was referring here is a typical ViewModel) which will have properties for internal usage of Controller/Business layer. That means they are not intended to display on UI. But when we use @Html.EditorFor, even those properties will  be scaffold automatically and displayed on UI.

Lets take an example of a simple Person class.

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

When we use this model with @Html.EditorFor –

@model IgnoreScaffoldDemo.Models.Person

@{
    ViewBag.Title = "CreatePerson";
}

<h2>CreatePerson</h2>

@Html.EditorFor(m => m)

We get following view –

image


But lets think that we do not want to expose Id as an UI element. In that case we can use [ScaffoldColumn(false)] to make Id not rendered on UI. So now we have person class as follows.

    using System.ComponentModel.DataAnnotations;
    public class Person
    {
        [ScaffoldColumn(false)]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

And the rendered UI would be like shown below.

image

 

Even the same logic applies to @Html.EditorForModel() too.

@model IgnoreScaffoldDemo.Models.Person

@{
    ViewBag.Title = "CreatePerson";
}

<h2>CreatePerson</h2>

@Html.EditorForModel()

Hope you find this JumpStart useful. Happy Coding!!!

You may also like...