Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 edit view for certain fields only

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.

like image 376
alpinescrambler Avatar asked Dec 30 '11 17:12

alpinescrambler


2 Answers

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.

like image 173
mreyeros Avatar answered Jan 02 '23 04:01

mreyeros


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.

like image 38
Craig Stuntz Avatar answered Jan 02 '23 03:01

Craig Stuntz