尝试将ViewModel用于Scaffold Controller会引发错误

时间:2017-09-08 03:21:00

标签: 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 = 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...
        };
      }

我尝试使用带有视图的MVC Controller创建一个控制器,使用Entity Framework。

enter image description here

然后我收到此错误:

enter image description here

我希望能够在视图中使用来自两个模型数据的数据......

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您无法使用PeopleStateViewModel创建脚手架,因为它没有定义主键(您需要使用数据库中的实际数据模型)。您可以在ID数据模型&amp;中添加KeyAttribute属性People。改为在这个数据模型上执行脚手架:

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; }
}

此外,在表单上的viewmodel中使用非参数构造函数提交HttpPost,如下所示:

[HttpPost]
public ActionResult ActionName(PeopleStateViewModel model)
{
    // do something
}

它将抛出此异常:

  

System.MissingMethodException:未定义无参数构造函数   对于这个对象。

要防止该错误,请在viewmodel类上使用declare a parameterless constructor

public class PeopleStateViewModel
{
    public People People { get; set; }
    public StatesDictionary States { get; set; }

    public PeopleStateViewModel()
    {
    }

    public PeopleStateViewModel(People people)
    {
        People = people;
        States = new StatesDictionary();
    }
}

答案 1 :(得分:1)

如评论中所述,域模型应该用在脚手架控制器和视图中。在您的情况下,在脚手架时使用People模型。创建控制器和视图后,开始修改控制器和视图以使用PeopleStateViewModel。