試了2天實在搞不定,上來跟前輩們求救一下~
一個DropDownList,一個按鈕,按更新POST回去Controller更新資料,但不懂為什麼DropDownList那邊會發生錯誤???
原始碼如下,錯誤報錯在View裡,不是在Controller裡
Controller
public ActionResult EditFinalPaper(int cId, int pId)
{
List<SelectListItem> PresentationListItem = new List<SelectListItem>();
PresentationListItem.Add(new SelectListItem { Text = "口頭發表(Oral)", Value = "1" });
PresentationListItem.Add(new SelectListItem { Text = "海報展示發表(Poster)", Value = "2" });
PresentationListItem.Add(new SelectListItem { Text = "口頭和海報發表皆可(Oral or Poster)", Value = "3" });
ViewBag.PresentationList = PresentationListItem;
Paper p = paperSrv.GetPaperInfo(pId);
return View(p);
}
[HttpPost]
public ActionResult EditFinalPaper(Paper paper)
{
if (ModelState.IsValid)
{
try
{
int PaperId = paperSrv.EditFinalPaper(paper);
return RedirectToAction("UploadFinalPaperFileP", "Paper", new { cId = paper.ConferenceId, pId = PaperId });
}
catch (Exception e)
{
throw;
}
}
return View(paper);
}
public int EditFinalPaper(Paper paper)
{
paper.LastUpdate = DateTime.Now;
db.SaveChanges();
return paper.PaperId;
}
View
@using (Html.BeginForm())
{
<div class="form-horizontal">
@Html.HiddenFor(model => model.ConferenceId)
@Html.HiddenFor(model => model.PaperId)
<div class="form-group">
<label for="Presentation" class="control-label col-md-2">論文發表方式(Presentation)</label>
<div class="col-md-9">
@Html.DropDownList("Presentation", (IEnumerable<SelectListItem>)ViewBag.PresentationList, "===請選擇===", new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="更新" class="btn btn-success" id="Update" onclick="if(confirm('確認更新?')) { return true; } else { return false; };" />
</div>
</div>
</div>
}
錯誤訊息
遇到這種Error真的不知道該怎麼解呀~在View裡中斷查錯也沒有得到有用的資訊!
找google大神的常見問題我也都避開了,還是一樣會Error~
我想很大問題是出在ViewBag.PresentationList這個東西出錯,但就不知道錯在那裡?要如何修正
其它頁面也都是用ViewBag來傳值沒問題
目前沒有方向了,上來求救一下~
在你的 http-post EditFinalPaper, PresentationListItem 不會再回來, 要再重新賦值.
所以改法應該會這樣
[HttpPost]
public ActionResult EditFinalPaper(Paper paper)
{
if (ModelState.IsValid)
{
try
{
int PaperId = paperSrv.EditFinalPaper(paper);
return RedirectToAction("UploadFinalPaperFileP", "Paper", new { cId = paper.ConferenceId, pId = PaperId });
}
catch (Exception e)
{
throw;
}
}
List<SelectListItem> PresentationListItem = new List<SelectListItem>();
PresentationListItem.Add(new SelectListItem { Text = "口頭發表(Oral)", Value = "1" });
PresentationListItem.Add(new SelectListItem { Text = "海報展示發表(Poster)", Value = "2" });
PresentationListItem.Add(new SelectListItem { Text = "口頭和海報發表皆可(Oral or Poster)", Value = "3" });
ViewBag.PresentationList = PresentationListItem;
return View(paper);
}
是不是你更新後
沒有給他ViewBag.PresentationList
又重新Render一次就報錯