forki23
forki23

Reputation: 2814

Using Html.EditorFor() for custom type in ASP.NET MVC

I have a custom type Money for my ViewModel:

public class Money
{
    public Money(decimal value)
    {
        Value = value;
    }

    public decimal Value { get; private set; }

    public override string ToString()
    {
        return string.Format("{0:0.00}", Value);
    }
}

and I want to render a textbox in ASP.NET MVC via HTML.EditorFor(viewModel => viewModel.MyMoneyProperty) but it doesn't work. Is there a special interface which I have to implement in Money?

Best regards and thanks in advance,

Steffen

Upvotes: 4

Views: 3378

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Try like this:

public class Money
{
    public Money(decimal value)
    {
        Value = value;
    }

    [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
    public decimal Value { get; private set; }
}

and in your view:

<%= Html.EditorFor(x => x.SomePropertyOfTypeMoney.Value) %>

Or you could have a custom editor template for Money (~/Views/Shared/EditorTemplates/Money.ascx):

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Money>" 
%>
<%= Html.TextBox("", Model.Value.ToString("0.00")) %>

and then in your view:

<%= Html.EditorFor(x => x.SomePropertyOfTypeMoney) %>

Upvotes: 3

Related Questions