我有兩個相似的ViewModel,我需要將其中一個投射到另一個。如何將ViewModel轉換爲另一個ViewModel?
這是第一個:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestInheritance.Models
{
public class ShowMatrixQuestionViewModel : ShowQuestionViewModel
{
public Dictionary<MatrixRows, List<MatrixColumns>> columnrow;
public List<MatrixColumns> columns;
public List<MatrixRows> rows;
public ShowMatrixQuestionViewModel()
{
columns = new List<MatrixColumns>();
rows = new List<MatrixRows>();
columnrow = new Dictionary<MatrixRows, List<MatrixColumns>>();
}
}
public class MatrixColumns
{
public int Column_ID { get; set; }
public int Column_Number { get; set; }
public String Column_Description { get; set; }
public Boolean IsAnswer { get; set; }
public int Procent { get; set; }
}
public class MatrixRows
{
public bool Delete { get; set; }
public int Row_Id { get; set; }
public String Row_Number { get; set; }
public String Row_Description { get; set; }
}
}
第二個看起來像這樣:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestInheritance.Models.ViewModels.New
{
public class ShowMatrixProcentViewModel : ShowMatrixQuestionViewModel
{
// Dette er for at vi kan bruge DisplayTemplates
public ShowMatrixProcentViewModel()
: base()
{
}
}
}
當我嘗試投了ShowMatrixQuestionViewModel到ShowMatrixProcentViewModel我得到一個InvalidCastException的:
MatrixColumns mc = new MatrixColumns()
{
Column_Description = "Hej",
Column_ID = 1,
Column_Number = 1,
IsAnswer = false
};
MatrixColumns mc2 = new MatrixColumns()
{
Column_Description = "Med",
Column_ID = 1,
Column_Number = 1,
IsAnswer = false
};
MatrixRows mr = new MatrixRows()
{
Row_Description = "2005",
Row_Id = 1,
Row_Number = "1"
};
MatrixRows mr2 = new MatrixRows()
{
Row_Description = "2008",
Row_Id = 1,
Row_Number = "2"
};
List<MatrixColumns> matrixcolumns = new List<MatrixColumns>();
matrixcolumns.Add(mc);
matrixcolumns.Add(mc2);
List<MatrixRows> matrixrows = new List<MatrixRows>();
matrixrows.Add(mr);
matrixrows.Add(mr2);
ShowMatrixQuestionViewModel avm = new ShowMatrixQuestionViewModel()
{
IsAnswered = true,
Question_ID = 1,
Question_Number = "1",
Question_Type = "hej",
Question_Wording = "spørgsmål1",
Visible = true,
columns = matrixcolumns,
rows = matrixrows
};
ShowMatrixProcentViewModel sm = (ShowMatrixProcentViewModel)avm;
return View(avm);
例外說:
System.InvalidCastException:無法強制類型爲「TestInheritance.Models.ShowMatrixQuestionViewModel」的對象類型爲「TestInheritance.Models.ViewModels.New.ShowMatrixProcentViewModel」。
我需要在ShowMatrixProcentViewModel中初始化一些東西,然後才能施放?
在此先感謝
肯慈你應該接受一個答案。 –
Tak爲hjælpen:)我還有一個未回答的問題:http://stackoverflow.com/questions/7706288/why-isnt-my-editortemplate-binding-a-list-on-httppost-but-renders-it-fine - 你認爲你可以幫忙嗎? – Kenci