2011-03-16 30 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方法。