Robert Morgan
Robert Morgan

Reputation: 665

ASP.NET MVC: How do I access my strongly-typed model from within a HtmlHelper extension method?

I can get at the ViewData and the ViewContext but not the Model.

Any ideas? Do I need to pass the model into the extension method as a parameter? Doesn't seem ideal.

Upvotes: 0

Views: 152

Answers (2)

tvanfosson
tvanfosson

Reputation: 532435

If you are depending on the type in the helper extension, I would prefer to have it passed as a parameter. This way you know that it has the proper type when you construct the method (won't compile if the model is not of the proper type). If you access it in the helper as a property of the ViewData, you won't know until runtime if it has the correct type and will be forced to throw an exception -- or handle it as an error. Neither of which are particularly good options, in my opinion.

Upvotes: 1

Robert Morgan
Robert Morgan

Reputation: 665

Found it!

helper.ViewData.Model

Upvotes: 2

Related Questions