Nick B
Nick B

Reputation: 715

Error on posting back editor fields with decimals

I get this error when I post back the fields below: Unable to cast object of type 'System.Decimal' to type 'System.String'.

The fields as part of the form:

<div class="editor-label">
        @Html.LabelFor(model => model.Donation.Amount)
    </div>    
    <div class="editor-field">
            @Html.TextBox("Amount", string.Format("{0:f2}", Model.Donation.Amount))
    <!--  @Html.EditorFor(model => model.Donation.Amount) -->
        @Html.ValidationMessageFor(model => model.Donation.Amount)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Pledge.PledgeTotal)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Pledge.PledgeTotal)
        @Html.ValidationMessageFor(model => model.Pledge.PledgeTotal)
    </div>

Both of which are decimal properties in the model... is it trying to post back as string then? Then how do I convert it back to a decimal before post back? Any thoughts? Thanks.

Upvotes: 1

Views: 683

Answers (1)

LukeP
LukeP

Reputation: 10422

Try this:

In your view model:

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

And in your view:

@Html.EditorFor(model => model.Donation.Amount)

Upvotes: 2

Related Questions