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
in your form and then use
to display the readonly value of the currency property. That way when you post the value will be sent along in the posted model.