从模型中设置模型的值

setting values of the model from a model

我有3个模型

第一个模型

public class BlogPosts
    {
        public int BlogID { get; set; }
        public int UserID { get; set; }
        public string PostTitle { get; set; }
        [AllowHtml]
        public string BlongContent { get; set; }
}

第二个模型

public class User
{
    public int User_ID { get; set; }
    public string User_Name { get; set; }
    public string User_Email { get; set; }
    public string Password { get; set; }
    public DateTime Registar_Date { get; set; }
}

这里是第三个模型,它应该完成获取和设置其他两个模型的值的工作,但是每当我尝试设置值时它 return 空引用异常。

 public class getModels
    {
        public BlogPosts post { get; set; }         
        public User user { get; set; }        

    }

示例控制器代码

 public ActionResult Index()
        {
            var m = new getModels();
            m.post.PostTitle = "Titlee of the post";
            ViewBag.tit = m.post.PostTitle;            
            return View();
        }

请提供任何帮助或指导

您的 geModels 属性未初始化。你可以只添加一个构造函数:

public getModels() 
{
    post = new BlogPost();
    user = new User();
}

或者在你的控制器中初始化它们

public ActionResult Index()
{
    var m = new getModels();
    m.post = new BlogPost();
    m.post.PostTitle = "Titlee of the post";
    ViewBag.tit = m.post.PostTitle;            
    return View();
}

BlogPostsUser 对象在 getModels class 中为 null。

要么在设置任何值之前初始化它们,要么在构造函数中使用代码来预初始化这两个对象:

public class getModels
{
     private BlogPosts _post;
     private User _user;
    
     public getModels()
     {
          this._post = new BlogPosts();
          this._user = new User();
     }
    
     public BlogPosts post { get{ return this._post; } set{ this._post = value; } }           
    
     public User user { get{ return this._user; } set{ this._user= value; } }
}

或者在操作中赋值之前初始化对象:

public ActionResult Index()
{
     var m = new getModels();
     m.post = new BlogPosts();
     m.post.PostTitle = "Titlee of the post";
     ViewBag.tit = m.post.PostTitle;            
     return View();
}

您可以使用自动属性执行相同操作:

public class BlogPosts
{
    public int BlogID { get; set; }
    public int UserID { get; set; }
    public string PostTitle { get; set; }
    [AllowHtml]
    public string BlongContent { get; set; }
}

public class User
{
    public int User_ID { get; set; }
    public string User_Name { get; set; }
    public string User_Email { get; set; }
    public string Password { get; set; }
    public DateTime Registar_Date { get; set; }
}

public class getModels
{
    public BlogPosts post { get; set; } = new BlogPosts();
    public User user { get; set; } = new User();
}