【问题标题】:ASP.NET MVC Model properties not in view returning nullASP.NET MVC 模型属性不在视图中返回 null
【发布时间】:2011-03-14 06:07:05
【问题描述】:

我有一个 EF Code First 模型,它具有这样的 ICollection 属性。

public class AccountProfile
{
    [Key]
    public int AccountID { get; set; }

    public string AccountName { get; set; }

    public string Email { get; set; }

    [Required]
    public virtual ICollection<UserProfile> LinkedUserProfiles { get; set; }
}

我将一个编辑视图绑定到这个模型,但它只显示 AccountName 和 Email 属性。

我有一个 HttpPost ActionResult 来更新采用 AccountProfile 的模型。

发布时,AccountProfile 对象仅填充了 AccountName 和 Email 属性。 LinkedUserProfiles 为空。这意味着无法更新模型,因为需要 LinkedUserProfiles 属性。

我也尝试过类似以下的方法,但没有任何运气

        var curAccountProfile = _accountProfileRepository.GetById(accountProfile.AccountID);

        TryUpdateModel(curAccountProfile);

我做错了什么?这种情况在MVC中应该如何处理?

更新 数据来自存储库,例如。

var accountProfile = _accountProfileRepository.ById(1);
return View(accountProfile);

在加载视图之前检查 accountProfile 对象表明正在检索集合 - 因此这不是延迟加载未按预期工作的情况。

我已经实现了 AutoMapper,为视图创建了一个 ViewModel,并将我的代码更改为如下所示:

var accountProfile = _accountProfileRepository.ById(accountInformation.AccountID);
var result = _mappingEngine.Map<DisplayAccountInformationViewModel, AccountProfile>(accountInformation, accountProfile);
_unitOfWork.Commit();

它现在按预期工作 - 但似乎比应有的努力更多?

【问题讨论】:

  • 您如何加载此编辑页面的数据?您可以发布您的查询方法吗?我认为问题在于延迟加载。

标签: asp.net-mvc entity-framework


【解决方案1】:

尝试即时加载LinkedUserProfiles

var curAccountProfile = _accountProfileRepository
     .GetById(accountProfile.AccountID)
     .Include(ap => ap.LinkedUsedProfiles);

看起来您正在使用存储库模式,所以不确定您如何处理急切加载。我的存储库返回IQueryable&lt;T&gt;Include 扩展方法对其有效。

如果您没有使用IQueryable&lt;T&gt;,那么您可能需要在存储库中进行预加载(例如接受布尔标志,例如:GetById(int id, bool include profiles)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2015-05-02
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多