4
我想在asp.net mvc5項目上工作,我有兩個模型Post和Game。asp.net值'1'無效
它會像這樣工作,你在帖子上發帖,你選擇你製作的遊戲,並且你也選擇你將要做的下一個遊戲。正如你可以將此圖片我已經得到了上看到的,所以你得到的遊戲是在數據庫中的一個DropDownList:
如何以往當我按下創建我得到一個錯誤說值「1」是無效的。
我不確定爲什麼會發生這種情況,因爲在我的數據庫中,我將這些值保存爲int。 郵政型號:
public class Post
{
[Key]
public int PostId { get; set; }
//URL
[Display(Name = "URL")]
[StringLength(80)]
[DataType(DataType.Url)]
[Required]
public string Url { get; set; }
//User
[Display(Name = "User")]
public virtual ApplicationUser User { get; set; }
//Game
[Display(Name = "Game")]
public virtual Game GameId { get; set; }
[Display(Name = "Next Game")]
public virtual Game NextGameId { 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;
}
}
}
柱控制器:
// GET: Posts/Create
public ActionResult Create()
{
ViewBag.GameId = new SelectList(db.Games, "GameId", "GameTitle");
ViewBag.NextGameId = new SelectList(db.Games, "GameId", "GameTitle");
return View();
}
// POST: Posts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "PostId,Url,GameId,NextGameId,Date")] Post post)
{
if (ModelState.IsValid)
{
db.Posts.Add(post);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.GameId = new SelectList(db.Games, "GameId", "GameTitle", post.GameId);
ViewBag.NextGameId = new SelectList(db.Games, "GameId", "GameTitle", post.NextGameId);
return View(post);
}
博弈模型:
public class Game
{
[Key]
public int GameId { get; set; }
public string GameTitle { get; set; }
}
而且我帖子/創建視圖其中I創建的下拉菜單:
<div class="form-group">
@Html.LabelFor(model => model.GameId, "GameId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("GameId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.GameId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.NextGameId, "NextGame", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("NextGameId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.NextGameId, "", new { @class = "text-danger" })
</div>
</div>
作品:'[顯示(名稱爲「遊戲」)] public虛擬遊戲GameId {get;組; }'應該是'int?'而不是'Game' – leppie
爲什麼你從你之前的問題中改變你的模型 - 現在'GameId'和'NextGameId'屬性是'Game'類型(一個複雜的對象)。將它們更改回「int」。並且不要將您的'ViewBag'屬性命名爲 –
調用導航屬性'GameId'和'NextGameId'會令人困惑。 – DavidG