I am learning ASP.Net MVC 5 , and I am stuck at usage of extention method
. So I created an extension method and now I want to use it in my Razor view. But it's throwing error InvalidOprationException Error.
Model
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[Display(Name = "Amount Owed")]
public decimal Amount { get; set; }
}
View
@model IEnumerable<WebApplication3.Models.Student>
@using WebApplication3.Extension
<table class="table" id="studentstable" style="border: 1px solid black; background-color: silver">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Amount)
</th>
<th>
@Html.DisplayNameFor(model => model.Amount)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@item.Amount.ConvertToDollar() @* this works fine *@
</td>
<td>
@Html.DisplayFor(modelItem => item.Amount.ConvertToDollar()) @*I want somwething like this so that I do not lose the HTML HELPERs*@
</td>
</tr>
}
</table>
Extension Method
namespace WebApplication3.Extension
{
public static class Helper
{
public static string ConvertToDollar(this decimal amount)
{
return String.Format("{0:C}", amount);
}
}
}
Error Line:
@Html.DisplayFor(modelItem => item.Amount.ConvertToDollar())
. I can use simply @item.Amount.ConvertToDollar()
But I want to embed it in HTMLHELPER. Please guide me. Is this even possible?