我正在學習MVC,並試圖創建一個簡單的表單,允許用戶更新模型的描述。MVC4 - 使用實體框架更新模型 - 空異常傳遞httpPost參數
問題是我得到一個空的異常
參數字典包含參數 空條目方法 「System.Web.Mvc非可空類型「System.Int32」的「ThreatID」 .ActionResult GetThreat(Int32)' 'RiskAssesmentApplication.Controllers.ThreatsController'。可選 參數必須是引用類型,可爲空類型,或者聲明爲可選參數 。參數名稱:參數
窗體的Get方法似乎按預期工作,但該ID沒有被傳回到HttpPost方法參數中,我無法工作應該如何傳遞它。跑了一次搜索,看到了一些關於使用@hiddenfor
助手的東西,但它對我來說並不適用。
這裏是我的方法
public ActionResult GetThreat(int ThreatID)
{
// ViewModel.Threat = repository.GetThreat(ThreatID);
RiskAssessmentApplicationEntities _DBContext = new RiskAssessmentApplicationEntities();
ThreatWithSecurityEventAndISOControlViewModel ViewModel = new ThreatWithSecurityEventAndISOControlViewModel();
ViewModel.Threat = _DBContext.Threats.Single(x => x.ID == ThreatID);
ViewModel.SecurityEvents = _DBContext
.ThreatHasSecurityEvents
.Include("ThreatHasSecurityEvent.SecurityEvent")
.Where(x => x.ThreatID == ThreatID)
.Select(x => x.SecurityEvent);
return View(ViewModel);
}
[HttpGet]
public ViewResult EditThreat(int ThreatID)
{
Threat Threat = repository.Threats.FirstOrDefault(x => x.ID == ThreatID);
return View(Threat);
}
[HttpPost]
public ActionResult EditThreat(Threat Threat)
{
if (ModelState.IsValid)
{
repository.SaveThreat(Threat);
TempData["message"] = string.Format("{0} new description has been saved", Threat.Description);
return RedirectToAction("GetThreat");
}
else
{
// something is incorrect!
return View(Threat);
}
}
這是我的看法
@model RiskAssesmentApplication.Threat
@using RiskAssesmentApplication;
@{
ViewBag.Title = "EditThreat";
}
<div style="font-family: Calibri">
<fieldset>
<legend>Edit Threat Description</legend>
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ID);
<div class="editor-label">
@Html.LabelFor(model => @Model.Description, "Threat Description")
</div>
<div class="editor-field">
@Html.EditorFor(model => @Model.Description)
@Html.ValidationMessageFor(model => @Model.Description)
</div>
<p>
<input type="submit" value="Save Changes" />
</p>
}
</fieldset>
</div>
這是我的模型
public class ThreatWithSecurityEventAndISOControlViewModel
{
public Threat Threat { get; set; }
public SecurityEvent SecurityEvent { get; set; }
public IEnumerable<ISOControl> ISOControls { get; set; }
public IEnumerable<SecurityEvent> SecurityEvents { get; set; }
真的難倒此所以任何幫助將不勝感激
該錯誤消息涉及的控制器方法'GetThreat()'但已示出的所有是'EditThreat()'方法 –
假設'GetThreat()'具有參數'int ThreatID',那麼它需要像'return RedirectToAction(「GetThreat」,new {ThreatID = Threat.ID});' - 但你需要顯示你的方法和模型以確保 –
嗨,謝謝你你的回覆,這個伎倆,我仍然會發布GetThreat()方法+模型以求清晰 –