samedi 17 décembre 2022

Get the count of Model Required properties that filled

In my ASP.NET MVC application, I have created a model for customer details to be saved in the database.

When I retrieved the data from the database in the controller, I want to get out of the required field how many fields were filled.

How to get this done on the controller?

This is done for an existing database, I'm building a new project based on that database.

So when retrieving the data from the database and passing the data to the view, I want to pass that out of the required fields, and this count is filled.

I can assign the required fields to count to a property.

Other count is needed to know how to get it.

This is an example model


[Key]
public int Id { get; set; } 

[Required]
[DisplayName("Surname")]
public string Sur_Name { get; set; }

[Required]
[DisplayName("Name")]
public string Name { get; set; }

[Required]
[DisplayName("Citizenship")]
public int Citizen_Country_Id { get; set; }

I have tried this, want to know if the way is correct.

int countRequired = customer.GetType().GetProperties().Select(x=>x.GetValue(customer,null)).Count(c=>c ==null);





Aucun commentaire:

Enregistrer un commentaire