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);
CodePudding user response:
You can use reflection for this, GetRequiredProperties
will give you all required properties and their type as key-value pair. then you can run a loop and get the value for each property. for the value type default value should be 0 and for the reference type, it should be null. you can add the check accordingly. I have left some code for you to try and figure it out with he given information.
public static Dictionary<string, System.Type> GetRequiredProperties<T>()
{
var info = TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute)))
.ToDictionary(p => p.Name, p => p.PropertyType);
return info;
}
foreach (var item in prop)
{
var value = obj.GetType().GetProperty(item.Key).GetValue(obj, null);
var type = item.Value;
}