【发布时间】:2018-02-19 02:40:44
【问题描述】:
我在模型中有一个属性需要是不可为空的。如果模型状态无效,则在提交表单时,我希望用户被重定向到同一页面。但是每当 ModelState 无效时,我都会收到异常
例外
参数字典包含“Bridge.Controllers.ReferrerController”中方法“System.Web.Mvc.ActionResult ReferralConfirmation(Int32)”的不可为空类型“System.Int32”的参数“referralId”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。 参数名称:参数
型号:
public class ReferrerInstanceViewModel
{
[Key]
public int Id { get; set; }
[FileType("pdf|doc|docx|PDF", ErrorMessage = "File type is not valid.")]
[Required]
public HttpPostedFileBase ProofDoc { get; set; }
[Required]
public int ReferralId { get; set; }
[Required]
public int? ReferralStatusId { get; set; }
public IEnumerable<SelectListItem> ReferralStatuses { get; set; }
}
控制器动作:
public ActionResult ReferralConfirmation(int referralId)
{
var viewModel = new ReferrerInstanceViewModel
{
ReferralId = referralId,
ReferralStatuses = _context.ReferralStatuses.Select(x => new SelectListItem
{
Text = x.ReferralStatusType,
Value = x.ReferralStatusId.ToString()
})
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ReferralConfirmation(ReferrerInstanceViewModel viewModel)
{
if (!ModelState.IsValid)
return RedirectToAction("ReferralConfirmation", viewModel.ReferralId);
// Some Logic
return RedirectToAction("ReferrerCenter");
}
查看:
@using (Html.BeginForm("ReferralConfirmation", "Referrer", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m=>m.ReferralId)
<div class="form-horizontal">
<h4>ReferrerInstanceViewModel</h4>
<hr />
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ReferralStatusId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.ReferralStatusId, Model.ReferralStatuses, "Reject Or Refer", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ReferralId, "*", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ProofDoc, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ProofDoc, new { type = "file" })
@Html.ValidationMessageFor(model => model.ProofDoc, "*", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
注意事项:
- 当 ModelState 无效时,我打电话给
RedirectToAction("ReferralConfirmation", I AM PASSING THE REQUIRED ReferralId VALUE HERE) - 当模型状态无效时,即使是 HTTPGET ReferralConfirmation Action 处的断点也不会被命中。
我无法理解这种行为。我在做什么错了。
请注意,在 ModelState 无效后生成的 Url 是
https://localhost:44328/Referrer/ReferralConfirmation
【问题讨论】:
标签: c# asp.net asp.net-mvc razor asp.net-mvc-5