2011-12-30 63 views
8

我有這樣的模式:MVC 3編輯觀點僅

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

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

@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.Currency)至@ Html.DisplayFor(型號=> model.Currency)不起作用,因爲模型的狀態變爲無效時,它回發給控制器。

回答

10

你可以在你的表單中添加

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

然後用

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

顯示貨幣屬性的只讀值。這種方式,當你發佈的價值將在發佈的模型中發送。

+0

這也可以與Twitter引導結合使用,例如,在視圖中使用下面的代碼:' @ Html.DisplayFor(m => m.ProductName)' – Manfred 2012-08-28 01:07:17

+1

用戶可以不通過螢火蟲等編輯read-olny字段嗎? – Sami 2013-10-04 09:34:35

4

您正在尋找:

[HiddenInput(DisplayValue=true)] 

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

它顯示值只讀,但添加一個隱藏的輸入,以使發佈狀態有效。

+0

用MVC 4嘗試了這一點,但沒有爲我工作,導致隱藏只。 EditorFor()不顯示任何內容。不過,我可能忽略了一些東西。我參加了爲我工作的@mreyeros解決方案。 – Manfred 2012-08-28 01:10:09

3

顯示貨幣,但不能編輯試圖

@Html.Label("Currency", Model.Currency) 

,如果你還需要發佈幣值回控制器嘗試

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

我希望這有助於。

+0

謝謝,我用這個解決方案 – alpinescrambler 2011-12-30 18:47:27

+0

如果你喜歡我的解決方案,請投票支持:) – 2012-01-04 16:06:38