2011-03-16 82 views
3

我遇到的問題是當我將填充對象傳遞給不顯示所有屬性的視圖時。未在視圖中使用的MVC 2模型屬性返回爲空或空

public ActionResult Edit(Guid clientID) 
{ 
    Property property = PropertyModel.GetPropertyDetails(clientID); 
    return View("Edit", "Site", property); 
} 

檢視:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<WebFrontend.ViewModels.Property>" %> 

<% using (Html.BeginForm()) 
    {%> 
    <%: Html.ValidationSummary(true, "Property update was unsuccessful. Please correct the errors and try again.") %> 

    <fieldset> 
     <legend>Edit Account: <%: Model.ClientAccountNo %></legend> 

     <div class="editor-label"> 
      <%: Html.LabelFor(model => model.ClientName)%> 
     </div> 
     <div class="editor-field"> 
      <%: Html.TextBoxFor(model => model.ClientName)%> 
      <%: Html.ValidationMessageFor(model => model.ClientName)%> 
     </div> 

     <p> 
      <input type="submit" value="Update Property" /> 
     </p> 
    </fieldset> 

<% } %> 

當提交的屬性對象被傳遞給該控制器的方法,但所有的視圖中未使用的屬性是空值或空白包括Model.ClientAccountNo其是存在於提交前查看。

[HttpPost] 
    public ActionResult Edit(Property property) 
    { 
     if (ModelState.IsValid) 
     { 
      bool success = PropertyModel.UpdateProperty(property); 
      if (success) 
      { 
       // property has been updated, take them to the property details screen. 
       return RedirectToAction("Details", "Property", new { clientID = property.ClientID }); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Could not update property."); 
       return View("Activate", "Site", property); 
      } 
     } 
     // If we got this far, something failed, redisplay form 
     return View("Edit", "Site", property); 
    } 

我在網上找不到任何類似的東西,任何解釋爲什麼會發生這種情況,以及如何解決它將不勝感激。

回答

2

這是MVC的工作方式 - 它嘗試從路由,表單和查詢字符串中的值構造操作參數類型的對象。在你的情況下,它只能得到表單集合中的值。它不知道你存儲在數據庫中的值。

如果您只對某些屬性感興趣,那麼您最好只使用這些屬性來製作特定的視圖模型 - 然後您可以驗證此特定案例。

如果您將值存儲在隱藏字段中,請記住可以操縱這些值 - 如果這是個問題,請務必使用僅包含可編輯字段的特定視圖模型。

+0

好吧,我現在看到,我有一種感覺,它不能以這種方式工作。我想我會結束視圖模型每個視圖路線只是意味着很多左手 - 右手編碼。 – WillMcKill 2011-03-16 16:35:02

1

由於您沒有在URL中傳遞未使用的屬性,因此您必須爲它們呈現隱藏的字段。使用Html.HiddenFor方法。