Programmatically adding properties to an MVC model at runtime

前端 未结 1 1278
你的背包
你的背包 2021-01-16 11:47

I am trying to create properties in my model programmatically when the application is run. I\'ve tried to follow the answer by Darin Dimitrov on this post How to create con

相关标签:
1条回答
  • 2021-01-16 12:05

    You are missing 2 hidden fields in your main view:

    @ModelType MyApp.DomainModel.MyTest.MyViewModel
    
    @Using Html.BeginForm()
        For i = 0 To Model.Controls.Length - 1
            @<div> 
                @Html.HiddenFor(Function(model) model.Controls(i).Type) 
                @Html.HiddenFor(Function(model) model.Controls(i).Name) 
                @Html.EditorFor(Function(model) model.Controls(i)) 
            </div> 
        Next
        @<input type="submit" value="OK" /> 
    End Using
    

    In your code you only have a single EditorFor call for the Controls property but you never specify the type of the control through a hidden field which is used by the custom model binder.


    UPDATE:

    I have also fixed the original model binder which contained a bug as it is better to override the CreateModel method instead of the BindModel:

    Public Class ControlModelBinder
    Inherits DefaultModelBinder
    Protected Overrides Function CreateModel(controllerContext As ControllerContext, bindingContext As ModelBindingContext, modelType As Type) As Object
        Dim type = bindingContext.ValueProvider.GetValue(Convert.ToString(bindingContext.ModelName) & ".Type")
        If type Is Nothing Then
            Throw New Exception("The type must be specified")
        End If
    
        Dim model As Object = Nothing
        Select Case type.AttemptedValue
            Case "textbox"
                If True Then
                    model = New TextBoxViewModel()
                    Exit Select
                End If
            Case "checkbox"
                If True Then
                    model = New CheckBoxViewModel()
                    Exit Select
                End If
            Case "ddl"
                If True Then
                    model = New DropDownListViewModel()
                    Exit Select
                End If
            Case Else
                If True Then
                    Throw New NotImplementedException()
                End If
        End Select
    
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(Function() model, model.[GetType]())
        Return model
    End Function
    End Class
    
    0 讨论(0)
提交回复
热议问题