【问题标题】:ASP.Net MVC Viewmodel Set Property value based on other propertyASP.Net MVC Viewmodel 根据其他属性设置属性值
【发布时间】:2013-11-05 12:55:01
【问题描述】:

我一直在阅读很多关于如何创建自己的 ASP.NET MVC DefaultModelBinder 的问题,这是我认为我需要的。

简而言之,我需要从模型属性中提取一些信息并将其添加到同一模型上的其他属性中。我认为最好在属性上有一个属性来告诉这是要从中提取的属性,然后指定另一个属性的名称,如下所示:

Public Class MyModel
    <MyAttribute(ExtraInfoProperty:="ExtraInfo")>
    Public Property MyProperty As String

    Public Property ExtraInfo As String
End Class

然后我会像这样创建自己的 DefaultModelBinder

Public Class MyModelBinder
    Inherits DefaultModelBinder

       Protected Overrides Sub SetProperty(controllerContext As System.Web.Mvc.ControllerContext, bindingContext As System.Web.Mvc.ModelBindingContext, propertyDescriptor As System.ComponentModel.PropertyDescriptor, value As Object)
        For Each attribute As Attribute In propertyDescriptor.Attributes
            If TypeOf attribute Is MyAttribute Then
                Dim extraInfo As String = ExtractExtraInfo(value)
                ' Set to ExtraInfo-property
            End If
        Next

        MyBase.SetProperty(controllerContext, bindingContext, propertyDescriptor, value)
    End Sub
End Class

但是 SetProperty 是正确的方法还是我需要覆盖 BindProperty 或其他东西?你会怎么做呢?

谢谢

【问题讨论】:

  • 您能否举例说明该属性将在何处使用?我觉得纯粹使用模型可能有更简单的方法。
  • 我可能在几个场景中需要它,例如我需要从电话号码中提取国家代码并将其放入不同的字段,即。 +358401234567 -> +358 和 0401234567。

标签: asp.net asp.net-mvc vb.net asp.net-mvc-4


【解决方案1】:

我认为这里不需要自定义绑定/属性的开销。如果ExtraInfo 的目的是简单地从另一个属性中获取额外的特定信息,为什么不将这些信息保留在模型本身中,例如

Public Class MyModel

    Public Property MyProperty As String

    Public Property ExtraInfo As String
        Get
            Return MyProperty.Substring(0, 4);
        End Get
    End Property

End Class

【讨论】:

  • 你可能是对的,这样的事情就足够了。但是如果你想做一个表格,国家代码和电话号码的字段在哪里。用户可以同时输入,或者如果他/她不输入并且国家代码嵌入到电话号码中,我想将其提取到第二个字段吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
相关资源
最近更新 更多