Using Html.EditorFor () for a Custom Type in ASP.NET MVC

I have my own 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 display the text box in ASP.NET MVC via HTML.EditorFor(viewModel => viewModel.MyMoneyProperty) , but it does not work. Is there a special interface that I have to implement in Money?

Best regards and thanks,

Steffen

+4
source share
1 answer

Try it 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 opinion:

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

Or you can create your own 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 opinion:

 <%= Html.EditorFor(x => x.SomePropertyOfTypeMoney) %> 
+3
source

Source: https://habr.com/ru/post/1341027/


All Articles