Asp.net mvc3 syntax syntax for translating a model into its subclass by reflection

I have a very simple question that I cannot find the answer to. In razor mode there is an interface model. This interface has several subclasses that implement it. The question arises: how can I apply a model to its actual type? I MUST have a variable of the actual type, but I don’t know how to get it from reflection That is.

@model IInterface
@{
   var actualType1 = Model as Model.GetType(); // doesn't work :(
   var actualType2 = (Model.GetType()) Model; // doesn't work :(
}

As you can imagine, I am not interested in Model as ActualTypeor (ActualType) Modelbecause I do not know which actual type comes in advance. His question is about technology, not about architecture.

Thanks in advance!

+1
source share
2 answers

. , , . :

var actualType1 = Model as Model.GetType(); 

, var , , , . , - , , - ( ).

, . , , , .

+2

, , OP, . , MetadataType.

public SomeViewModel
{
  public string FormField { get; set; }
  public string FormField2 { get; set; }
}

public interface IAnonymousSomeViewModel
{
  [Required]
  public string FormField { get; set; }
  [Scaffold(false)]
  public string FormField2 { get; set; }
}


public interface IUserSomeViewModel
{
  [Scaffold(false)]
  public string FormField { get; set; }
  [Required]
  public string FormField2 { get; set; }
}

[MetadataType(typeof(IAnonymousSomeVieModel)]
public AnonymousViewModel : SomeViewModel { }


[MetadataType(typeof(IUserSomeVieModel)]
public UserViewModel : SomeViewModel { }

AnonymousViewModel, UserViewModel, :

@model SomeViewModel

@Html.EditorFor(m => m.FormField)

@Html.EditorFor(m => m.FormField2)
0

All Articles