2013-07-18 39 views
0

稱我瘋了,但這似乎令人難以置信的多餘和不必要的,但對於我的生活,我無法找到實現這兩個功能的功能。顯示HTML中的內容。隱藏或保存顯示

using Html.BeginForm("Save, Home") { 


    @Html.DisplayFor(x => x.Id) 
    @Html.HiddenFor(x => x.Id) 

    @Html.DisplayFor(x => x.CreatedDate) 
    @Html.HiddenFor(x => x.CreatedDate) 

    //Useful fields below 

} 

讓我解釋 - 我想保存CreatedDate和Id值,因此隱藏。這當然會在幕後生成輸入,但我也需要顯示它。 DisplayFor和ValueFor都在我的表單提交中返回Id = 0。更具體地說,當我更新表單中的數據時,我想保留這兩個值。返回的模型有他們在0 /日期時間年0.

是否沒有辦法保存這些值爲下一個模型?

回答

2

您可以創建一個擴展方法:

public static class HtmlHelperExtensions 
{ 
    public static IHtmlString DisplayAndHiddenFor<TModel, TProperty>(
     this HtmlHelper<TModel> helper, 
     Func<TModel, TProperty> propertyAccessor) 
    { 
     return new HtmlString(
      helper.DisplayFor(propertyAccessor).ToHtmlString() 
      + helper.HiddenFor(propertyAccessor).ToHtmlString()); 
    } 
} 

像這樣來使用(當然是正確的using):

@Html.DisplayAndHiddenFor(x => x.Id) 
@Html.DisplayAndHiddenFor(x => x.CreatedDate)