0

Inside a razor page, I must know whether a model property is decorated by [Required].

The conventional answer is:

@{
  var isNameRequired = 
    Context
    .RequestServices.GetRequiredService<IModelExpressionProvider>()   // yuck!
    .CreateModelExpression(ViewData, x => x.Company.Details.Name)
    .Metadata
    .IsRequired;
}

That uses the service locator anti-pattern. (I realise I could inject that service instead, but want to avoid another dependency for something so simple).

Is there another way to do this?

There is plenty of detail in the page's ViewData, but there's no way (I can find) to use a lambda expression (x => x.Company.Details.Name) to drill down into the property I want. It's in there, I just can't find a way to get it using a lambda instead of a magic string.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.