ASP MVC - Cast ViewModel object for another type

I have a ViewModel like this:

public class Column {

    public string Name;

    public string Type;

    public object Content;

}

The content can be int, string ... Depending on the Type, I call a specific EditorTemplate: Column_int, Column_string ... no problem.
However, I have a GeoPoint type that I also want to use, with the corresponding EditorTemplate Column_GeoPoint column. The problem is that in my controller when the ViewModel is dispatched when I do this:

GeoPoint geoPoint = ((GeoPoint) mViewModel.Content);

I get an exception for an exception.
Any ideas on how to include an object in another in the ViewModel?

+4
source share
3 answers

GeoPoint cast. GeoPoint, google , , , , .

/ ( ).

- , :

public class ColumnViewModel {
    public string Name;
    public string Type;
    public string ContentString;
    public int ContentInt;
    public GeoPoint ContentGeoPoint;
}

.. , "" .

DTO :

public class Column {
    public string Name;
    public string Type;
    public object Content;
}

public ActionResult PostAction(ColumnViewModel model)
{
    var dto = new Column();
    switch (model.Type)
    {
        case "int": 
            dto.Content = dto.ContentInt;

        case "geo": 
            dto.Content = dto.ContentGeoPoint;
            break;

       // etc
    }
}

, ( ) - . , .

0

ToGeoPoint() .

:

public class Column {

    public string Name;

    public string Type;

    public object Content;

    public GeoPoint ToGeoPoint() {
        GeoPoint point = new GeoPoint();
        point.Name = this.Name;
        point.Type = this.Type;
        point.Content = this.Content;
        return point;
    }

}

, , GeoPoint . , , , .

0

Source: https://habr.com/ru/post/1625988/


All Articles