问题
Right now I can create games under the Games/Create. And I can make a post under Post/Create.
But my problem is that right now my public int GameId { get; set; }
gets populated with the items that is in my Game table in my SQL database. Which is just fine that's how I like it.
But I want public string Title { get; set; }
to the populated the same way with the values that are in the Game database.
public int GameId { get; set; }
gets populated with a dropdownlist with the values that is in my Game table.
And as for public string Title { get; set; }
I have to enter it manually. I want that to be populated the same way as GameId
This is my Post Model
public class Post
{
[Key]
public int PostId { get; set; }
//URL
[Display(Name = "URL")]
[StringLength(80)]
public string Url { get; set; }
//User
[Display(Name = "User")]
public virtual ApplicationUser User { get; set; }
//Game
[Display(Name = "Game")]
public int GameId { get; set; }
[Display(Name = "Next Game")]
public string Title { get; set; }
public virtual Game Game { get; set; }
//Time
private DateTime? _date;
public DateTime? Date
{
get
{
if (_date == null || _date.ToString() == "1/1/0001 12:00:00 AM")
{
return _date = DateTime.Now;
}
return _date;
}
set
{
_date = value;
}
}
And this is my Game Model
public class Game
{
[Key]
public int GameId { get; set; }
//Game
[Display(Name = "Game")]
public string Title { get; set; }
//User
[Display(Name = "User")]
public virtual ApplicationUser User { get; set; }
}
回答1:
Actually you don't need your property Title in your Post Model, in your controller you can do something like this to get all data of Game.
using (var db = new YourDbContext())
{
var post = db.Posts().Include(g => g.Game).FirstOrDefault();
var gameTitle = post.Game.Title;
}
来源:https://stackoverflow.com/questions/31112062/populate-a-mvc5-list