I have this model:
public class ExchangeRate
{
    [Key]
    public  int ExchangeRateID { get; set; }
    [Required]
    [Display(Name = "Currency:")]
    public  string Currency { get; set; }
    [Required]
    public  decimal Rate { get; set; }
}
The "Create" view is working fine, but when I am in the edit view, I only want the Currency property to be displayed, and not editable. How should I do this? If I create another "view-only" model for this class, then I would omit the "Currency" property and would not be able to display it.
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>ExchangeRate</legend>
    @Html.HiddenFor(model => model.ExchangeRateID)
    <div class="editor-label">
        @Html.LabelFor(model => model.Currency)
    </div>
    <div class="editor-field">
         @Html.DisplayFor(model => model.Currency)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Rate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Rate)
        @Html.ValidationMessageFor(model => model.Rate)
    </div>
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}
Changing @Html.EditorFor(model => model.Currency) to @Html.DisplayFor(model => model.Currency) doesn't work because the model state becomes invalid when it posts back to the controller.
You could add
@Html.HiddenFor(model => model.Currency)
in your form and then use
@Html.DisplayFor(model=> model.Currency)
to display the readonly value of the currency property. That way when you post the value will be sent along in the posted model.
You're looking for:
[HiddenInput(DisplayValue=true)]
Then show the editor, not the display (use EditorFor).
This displays the value read-only, but adds a hidden input so that the posted state is valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With