PilotBob
PilotBob

Reputation: 3117

How do I access ModelState in a Razor Helper

I have created a razor helper using the

@helper MyHelper(string param) {
}

syntax. I need to be able to access the model state to determine if I should add error classes to the elements. How would I access this? Intellisense does show ModelState but it is always null.

In a razor page I would use ViewData.ModelState but ViewData doesn't exist in the context.

Upvotes: 0

Views: 536

Answers (1)

Shyju
Shyju

Reputation: 218732

You need to explicitly pass the view context from the view when you call this helper method.

@helper MyHelper(string param,ViewContext context) {
  <div>
    @foreach (var modelStateVal in context.ViewData.ModelState.Values)
    {
        foreach (var error in modelStateVal.Errors)
        {
           <p>@error.ErrorMessage</p>
        }
    }
  </div>
}

and in the view where you want to call this,

@MyHelperClass.MyHelper("Hello",this.ViewContext)

Another option is to create an Html Hepler method

Upvotes: 2

Related Questions