Asp.net mvc 尝试使用ViewModel构建控制器引发错误
对ASP.net Core 2 MVC非常陌生,但正在尝试解决问题 我创建了一个ViewModel:Asp.net mvc 尝试使用ViewModel构建控制器引发错误,asp.net-mvc,visual-studio,asp.net-core-mvc,Asp.net Mvc,Visual Studio,Asp.net Core Mvc,对ASP.net Core 2 MVC非常陌生,但正在尝试解决问题 我创建了一个ViewModel: ublic class PeopleStateViewModel { public People People { get; set; } public StatesDictionary States { get; set; } public PeopleStateViewModel(People people) { People = peopl
ublic class PeopleStateViewModel
{
public People People { get; set; }
public StatesDictionary States { get; set; }
public PeopleStateViewModel(People people)
{
People = people;
States = new StatesDictionary();
}
}
我有这两种型号:
public class People
{
public int ID { get; set; }
[StringLength(60, MinimumLength = 2)]
[Required]
public string FirstName { get; set; }
[StringLength(60, MinimumLength = 2)]
[Required]
public string LastName { get; set; }
}
public static SelectList StateSelectList
{
get { return new SelectList(StateDictionary, "Value", "Key"); }
}
public static readonly IDictionary<string, string>
StateDictionary = new Dictionary<string, string> {
{"Choose...",""}
, { "Alabama", "AL" }
, { "Alaska", "AK" }
, { "Arizona", "AZ" }
, { "Arkansas", "AR" }
, { "California", "CA" }
// code continues to add states...
};
}
公共阶层人士
{
公共int ID{get;set;}
[StringLength(60,最小长度=2)]
[必需]
公共字符串名{get;set;}
[StringLength(60,最小长度=2)]
[必需]
公共字符串LastName{get;set;}
}
公共静态SelectList状态SelectList
{
获取{returnnewselectlist(StateDictionary,“Value”,“Key”);}
}
公共静态只读IDictionary
StateDictionary=新字典{
{“选择…”,“}
,{“阿拉巴马州”、“阿尔卑斯州”}
,{“阿拉斯加”,“AK”}
,{“亚利桑那州”,“亚利桑那州”}
,{“阿肯色州”,“阿肯色州”}
,{“加利福尼亚州”,“加利福尼亚州”}
//代码继续添加状态。。。
};
}
我尝试使用实体框架,通过视图使用MVC控制器创建一个控制器
然后我得到这个错误:
我希望能够使用来自两个模型的数据在一个视图上的数据
感谢您的帮助 如评论中所述,域模型应在脚手架控制器和视图中使用。在您的案例中,在搭建脚手架时使用人员模型。创建控制器和视图后,开始修改控制器和视图以使用PeopleStateViewModel。您不能使用
PeopleStateViewModel创建脚手架,因为它没有定义主键(您需要使用数据库中的实际数据模型)。您可以在People
数据模型中使用KeyAttribute
添加ID
属性,并在该数据模型上执行脚手架:
public class People
{
[Key]
public int ID { get; set; }
[StringLength(60, MinimumLength = 2)]
[Required]
public string FirstName { get; set; }
[StringLength(60, MinimumLength = 2)]
[Required]
public string LastName { get; set; }
}
另外,在表单submit上的viewmodel中使用非无参数构造函数,并使用HttpPost
,如下所示:
[HttpPost]
public ActionResult ActionName(PeopleStateViewModel model)
{
// do something
}
它将抛出此异常:
System.MissingMethodException:未定义无参数构造函数
对于这个对象
要防止该错误,请在viewmodel类上执行以下操作:
public class PeopleStateViewModel
{
public People People { get; set; }
public StatesDictionary States { get; set; }
public PeopleStateViewModel()
{
}
public PeopleStateViewModel(People people)
{
People = people;
States = new StatesDictionary();
}
}
PeopleStateViewModel
viewmodel当然没有任何主键字段,因此无法构建它。使用实际数据模型而不是视图模型来执行支架。视图模型与数据上下文没有关系。另外,它们不包含作为数据模型的属性,只包含视图中所需的数据模型属性。您的视图模型将在POST方法中引发异常,因为它没有无参数构造函数