Sunday, June 30, 2013

MVC: Issue with Custom Html Extensions

Recently, I was tasked with creating a custom HTML helper for displaying the names of a model's property with spaces. For example, if a model has a property VehicleMake, I should be able to use 

@Html.DisplayNameForWithSpaces(model => model.CarModel)

on the view instead of using a <label> and typing "Vehicle Make" manually.
So I created a static class and wrote down this method as shown below.


On the View which required this functionality to be used, I added the namespace as

@using <Namespace containing the Html extensions>

However, in spite of adding this, I was not able to access the method "DisplayNameForWithSpaces". On hunting high and low from stackoverflow to  ASP.NET MVC forums for almost 4 hours, I compared it with another project i had used it in.
Then the issue dawned upon me. 

THE ISSUE: The issue was a very simple one. If you look at the method signature, the first parameter is an IEnumerable<TModel>, which basically means that the model that is bound on the view on which we are using this extension must be an IEnumerable collection.
However, the model for which I had used this extension method was not an IEnumerable. It was a details view on which I just had to show details of the selected item.

THE SOLUTION: The solution was just to use the overloaded html extension method as shown below.




As shown by the highlighted square, this overload contains a HtmlHelper<TModel> instead of HtmlHelper<IEnumerable<TModel>>

CONCLUSION: So, the conclusion is that be very careful while adding a new Html Extension method. The extension is dependent on the whether the model on the View(on which this extension method is intended to be used) is a single entity or an IEnumerable collection. Based on this, we may selected either of the overloads provided.

Happy learning! :)



No comments:

Post a Comment