dimanche 26 mars 2023

ASP.NET MVC Nested Object Reflection for Hidden Values

I'm trying to figure out the best way to generate hidden values for nested objects to post on a form without any hardcoding. In other words, some partial view would just take in a model and generate hidden values for the lowest fields of the hierarchy.

Here's a basic example to illustrate what I'd like to do:

public class SomeModel {

    public ClassA firstClass { get; set; } = null!;

}
public class ClassA {
    
    public ClassB secondClass { get; set;} = null!;

}
public class ClassB {

    public ClassC thirdClass { get; set; } = null!;

}

public class ClassC {

    public string? someText { get; set;}

}

I would like to be able to generate the hidden value that represents the someText field within ClassC to model bind to the SomeModel class when the form is submitted, so it should look something like this:

<input type="hidden" name="firstClass.secondClass.thirdClass.someText" value="test" />

From what I can understand, some sort of reflection/recursion might be able to achieve this type of behavior without hardcoding. Ideally, the solution would be scalable to any number of nested objects and hidden values.

Thanks





Aucun commentaire:

Enregistrer un commentaire