我正在学习MVC并尝试创建一个简单的表单,允许用户更新模型的描述。
问题是我得到一个空例外
参数字典包含参数的空条目 方法的非可空类型'System.Int32'的'ThreatID' 'System.Web.Mvc.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; }
我真的很难过,所以任何帮助都会受到赞赏
答案 0 :(得分:2)
您的Long.MAX_VALUE
方法期望参数Math.pow(2, 63)
(不可为空)但在您的GetThreat()
方法中,重定向时不传递值。变化
int ThreatID
到
EditThreat()
答案 1 :(得分:0)
如果没有看到你的其余代码,很难肯定地说,但听起来你正在使用断开连接的实体。仅仅因为您正在使用数据库中具有行ID的实体模型并不意味着它已连接到您的数据上下文。使用在帖子中传回的模型来查找连接的版本。例如:
[HttpPost]
public void Whatever(Threat model)
{
var connectedModel = context.Threats.FirstOrDefault(x => x.ID == model.ID);
connectedModel.SomeProperty = model.SomeProperty; //or use AutoMapper
context.SaveChanges();
}
答案 2 :(得分:0)
将RedirectToAction
替换为:
return RedirectToAction("EditThreat", new { ThreatID = 99 });