2013-03-30 27 views
0

我使用4個字符串字段聲明模型。其中3個是隻讀的形式:MVC模型不會以表格形式存在

public class HomeModel 
    { 
     [ReadOnly(true)] 
     [DisplayName("Service Version")] 
     public string ServiceVersion { get; set; } 

     [ReadOnly(true)] 
     [DisplayName("Session Id")] 
     public string SessionId { get; set; } 

     [ReadOnly(true)] 
     [DisplayName("Visiting from")] 
     public string Country { get; set; } 

     [DisplayName("Search")] 
     public string SearchString { get; set; } 

    } 

我通過模型,填充它後,我的表格:

[HttpGet] 
     public ActionResult Index() 
     { 
      var model = new HomeModel 
          { 
           Country = "Australia", 
           SearchString = "Enter a search", 
           ServiceVersion = "0.1", 
           SessionId = "76237623763726" 
          }; 
      return View(model); 

     } 

,並顯示形式如我所料:

<h2>Simple Lookup</h2> 

@Html.LabelFor(m=>m.ServiceVersion): @Model.ServiceVersion<br/> 
@Html.LabelFor(m=>m.SessionId): @Model.SessionId<br/> 
@Html.LabelFor(m=>m.Country): @Model.Country<br/> 
<p> 
    @using(Html.BeginForm()) 
    { 
     @Html.LabelFor(m => m.SearchString) 
     @Html.TextBoxFor(m => m.SearchString) 
     <button type="submit" name="btnSearch">Search</button> 
    } 
</p> 

但是,當我提交表單並從表單中取回模型時,只填充了SearchString的值。

[HttpPost] 
public ActionResult Index(HomeModel model) 
{ 
    return View(model); 
} 

是不是正確的是其他領域已經'失去'? MVC不保存模型類的其他成員嗎?如果這是預期的 - 有沒有辦法重新獲得這些?或者我需要返回到我的數據庫,使用舊值填充模型,然後使用表單模型中的新值?

想要從模型中讀取「只讀」字段的有效性被質疑。這是公平的 - 但是如果我發現有關發佈數據的可疑信息,顯示屏幕,而不必重新讀取數據庫中的數據?

+0

[只讀(true)] 表示該屬性是隻讀的,因此不會與回發的值綁定 –

回答

0

這是正確的行爲。只有表單中的元素纔會發佈到您的操作中。由於它發佈了表單,所以你的字段應該放在表單中以便讓它們在你的發佈方法中。

更新

而且,你不能在你的操作方法,如果您有隻讀採取現場對您的視圖閱讀特定領域。例如:使用@Html.LabelFor進行顯示。如果字段不被編輯,爲了讓您的行動回到現場,請使用@Html.HiddenFor

+0

我將其他字段移至表單中 - 但得到同樣的問題。也許他們不應該在模型中是隻讀的? – Craig

+0

是的。您無法在您的發佈方法中重新獲得只讀字段。 –

+0

好的,謝謝。所以,如果我需要將該字段看作標籤,並將其返回到模型,則應同時使用HiddenFor(用於發佈)和DisplayFor(用於顯示)? – Craig