4

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

1 Answer 1

3

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) %>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this helped me a lot. I added a Text property and did the converting stuff in the getter and setter. Then I bound it in the view.
One problem still remains. Now all ids in the HTML code are suffixed with _text. How can I avoid this?
@forki23, this happens because you added a Text property and the textbox helper is using it. You might need a custom helper that modifies the ids but this is something I wouldn't do. Leave the helper generate whatever ids it like because this way they will be guaranteed to be unique. If you start messing with the ids there is a risk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.