Asp.net-Mvc-3

僅針對某些欄位的 MVC 3 編輯視圖

  • March 15, 2017

我有這個模型:

public class ExchangeRate
{
   [Key]
   public  int ExchangeRateID { get; set; }
   [Required]
   [Display(Name = "Currency:")]
   public  string Currency { get; set; }
   [Required]
   public  decimal Rate { get; set; }
}

“創建”視圖工作正常,但是當我在編輯視圖中時,我只希望顯示貨幣屬性,而不是可編輯的。我該怎麼做?如果我為這個類創建另一個“僅查看”模型,那麼我將省略“貨幣”屬性並且無法顯示它。

@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>

}

將 @Html.EditorFor(model => model.Currency) 更改為 @Html.DisplayFor(model => model.Currency) 不起作用,因為模型狀態在回發到控制器時變得無效。

你可以添加

@Html.HiddenFor(model => model.Currency)

在您的表格中,然後使用

@Html.DisplayFor(model=> model.Currency)

顯示貨幣屬性的只讀值。這樣,當您發佈時,值將在發布的模型中發送。

您正在尋找:

[HiddenInput(DisplayValue=true)]

然後顯示編輯器,而不是顯示(使用EditorFor)。

這會以只讀方式顯示值,但會添加隱藏輸入,以便發布的狀態有效。

引用自:https://stackoverflow.com/questions/8682417