需要在控制器中设置参数,但ModelState.IsValid为false

时间:2016-02-23 07:24:39

标签: c# asp.net asp.net-mvc entity-framework

我有一个视图(表单),允许用户在我的ASP.NET MVC 5 Web应用程序中创建一个新的模型项。有4个字段需要在此模型上进行设置,但表单仅设置3,因为第4个在控制器中以编程方式设置。第4个属性是AspNetUser表(当前经过身份验证的用户)的foriegn密钥

public class Student
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [Required(AllowEmptyStrings=false)]
    public String FirstName{ get; set; }

    [Required(AllowEmptyStrings=false)]
    public String LastName { get; set; }

    //not setting this in the view is causing an error. 
    [Required(AllowEmptyStrings=false)]
    public virtual ApplicationUser UserAccount { get; set; }

    // this doesn't need to be set by anyone creating a Student 
    public virtual ICollection<Course> Courses {get;set;}
}

我在Create action / route中设置视图,如下所示:

var userID = User.Identity.GetUserId();

student.UserAccount= (from t in db.Users
                        where t.Id == userID
                        select t).Single();

不幸的是ModelState.IsValid是假的,因为用户未在视图中设置第4个属性(UserAccount)(如果我检查ModelState上的错误,我可以看到这个)。

这里有什么正确的解决方案?我做了什么菜鸟吗?

由于

0 个答案:

没有答案