Ignore some fields using the helper @Html.EditorForModel()
Asked Answered
C

3

12

I use helper @Html.EditorForModel() on all my views.

There is a desire that he skip two fields in my model, but only on this view, the other he must continue to display these fields as usual.

How can I skip these two fields only in this view?

Conciliar answered 28/7, 2011 at 14:18 Comment(1)
@Nicholas, well its much better than mine! (alhough mine is quicker to put on forms/email addresses!)Empty
Y
32

Use the [ScaffoldColumn(false)] attribute.

E.g.

public class Person {
    [ScaffoldColumn(false)]
    public int PersonID { get; set; }
    ...

Solution and example sourced from: Pro ASP.NET MVC 3 Framework, Third Edition

Yiyid answered 19/9, 2011 at 6:54 Comment(0)
O
3

I'd recommend writing viewmodels for any view that you want to deviate from default behaviour.

Side note: It's probably a good idea to write a viewmodel for every view, as you get separation of concerns, and it's easier to control the behaviour of each view.

Anyway...

For example, say your model is

class Herps {
    public string Name { get; set; }
    public int SecretToSomePeople { get; set; }
}

and you don't want to have SecretToSomePeople shown on one of your views, create a viewmodel that doesn't contain SecretToSomePeople

class Herps {
    public string Name { get; set; }
}

and use that as the model for the desired view. Make sure you copy to/from the actual model somewhere though.

Outhouse answered 28/7, 2011 at 14:46 Comment(0)
E
1

Strictly speaking, if you don't want to display the fields then they shouldn't be on the Model - the point of Models to to hold exactly the data required for the View.

Empty answered 28/7, 2011 at 14:44 Comment(4)
There are two steps. In the first step, the user fills only part of the information in the second it fills the rest. The fields are displayed in another view;Conciliar
I do not agree with you - this is a ViewModel and therefore it should contain all the data neccessary for the view to be displayed properly. It does not mean that all data should be edited/updated by the user.Weeden
@MaksymilianMajer: that's not what he's saying - he has a viewmodel with n fields on it, but only wants to show n-2 fields. The other two are irrelevant for this particular view. Nicholas Sizer explains it better below.Empty
You are right. I wanted to stress out a situation when he might need those properties to affect how the view is rendered but still not be visible when using EditorForModel(). The original question doesn't eliminate this possibility but your answer does.Weeden

© 2022 - 2024 — McMap. All rights reserved.