Reputation: 15
I have 3 models
1st Model
public class BlogPosts
{
public int BlogID { get; set; }
public int UserID { get; set; }
public string PostTitle { get; set; }
[AllowHtml]
public string BlongContent { get; set; }
}
2nd Model
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; }
}
and here is 3rd model which suppose to do a job of getting and seting values of other two models but it return null reference exception whenever i try to set the values.
public class getModels
{
public BlogPosts post { get; set; }
public User user { get; set; }
}
Sample Controler code
public ActionResult Index()
{
var m = new getModels();
m.post.PostTitle = "Titlee of the post";
ViewBag.tit = m.post.PostTitle;
return View();
}
Any kind of Help or guidance please
Upvotes: 0
Views: 1131
Reputation: 14846
You can do the same using auto properties:
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();
}
Upvotes: 1
Reputation: 3244
The BlogPosts
and User
object is null in the getModels
class.
Either initialize those before setting any value or have codes in the constructor to pre-initialize the two objects:
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; } }
}
Or initialize the object before assigning the values in the action:
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();
}
Upvotes: 1
Reputation: 9318
Your geModels
properties are not initialized. you could just add a constructor:
public getModels()
{
post = new BlogPost();
user = new User();
}
or initialize them in you contorller
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();
}
Upvotes: 1