代码之家  ›  专栏  ›  技术社区  ›  gfrizzle

在未加载所有字段时,在强类型视图上保存数据的最佳方法

  •  0
  • gfrizzle  · 技术社区  · 16 年前

    假设我有一个编辑视图,它强类型化到一个名为“MyData”的表中。视图有多个选项卡,每个选项卡都有表中的几个不同字段。出于性能考虑,只有在查看选项卡时才会加载数据,因此如果仅编辑选项卡1上的字段并提交表单,则不会加载选项卡2的数据。

    我遇到的问题在提交上。我正在执行在数据库中查找现有记录并更新传递值的典型例程:

    <AcceptVerbs(HttpVerbs.Post)> _
    Function Edit(ByVal data As MyData) As ActionResult
    
        Using dc = New MyDataContext
            Dim orig = dc.MyDatas.Single(Function(x) x.id = data.id)
            orig.name = data.name
            orig.desc = data.desc
            ...
            SubmitChanges()
        End Using
    
        Return View(orig)
    
    End Function
    

    但是,此方法不知道加载了哪些选项卡,因此,如果未加载带有“desc”的选项卡,则此方法认为用户已清除“desc”字段,并向数据库发送NULL。

    3 回复  |  直到 16 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    你有什么理由不使用它吗 UpdateModel(orig) ?

    如果您使用的是模型绑定,而不是手动检查表单内容并分配值,那么这将为您解决。默认的模型绑定行为是忽略没有相应表单值的属性。

    你可能想看看 this post

        2
  •  0
  •   Eric Petroelje    16 年前

        3
  •  0
  •   JOBG    16 年前

    在这里,ViewModel模式可能会对您有所帮助,您可以像选项卡视图一样拆分原始模型:

    public class Tab1 
        {
            public string pproperty1 { get; set; }
            public string pproperty2 { get; set; }
        }
        public class Tab2
        {
            public string pproperty3 { get; set; }
            public string pproperty4 { get; set; }
        }
        public class Tab3
        {
            public string pproperty5 { get; set; }
            public string pproperty6 { get; set; }
        }
        public class ViewModels
        {
            public Tab1 TAB1 { get; set; }
            public Tab2 TAB2 { get; set; }
            public Tab3 TAB3 { get; set; }
        }
    

    Tab2 == null 然后您就知道用户没有加载或更改这些属性。

    推荐文章