data annotations hide property/field

2020-07-11 09:12发布

问题:

I have a model

class Address {
 public int AddressID {get;set;}
 public string Street {get;set;}
 public string City {get;set;}
 public string State {get;set;}
 public int ZipCode {get;set;}
}

in my view, when I have

@Html.LabelFor(model => model.Address) (assuming Address is a complex property inside another model)

I get a label for every one of Address properties, so I get:

AddressID:

Street:

City:

State:

ZipCode:

problem is, I don't want the ID property to show up, I tried these two annotations:

[Display(AutoGenerateField = false)]
[HiddenInput(DisplayValue = false)]

but the first one doesn't do anything for some reason, and the HiddenInput keeps getting a red squiggly line, not sure if they both use the same System.ComponentModel.DataAnnotations assembly

回答1:

just found the answer actually..

[HiddenInput(DisplayValue = false)] works but I had to add:

using System.Web.Mvc;


回答2:

as for me, when I'm used

[HiddenInput(DisplayValue = false)]

to my model props I still got displaying in schaffolded Create/Edit views. When I was just removing that code from view - yes, it wasn't visible any more, but after saving edits I got another problem: props for what I remove editors change their values to null. I use this on edit views to fix it

@Html.HiddenFor(model => model.ImageUrl)