简体   繁体   中英

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

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) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM