【发布时间】:2020-06-02 22:23:26
【问题描述】:
我想在我的模型中的属性上捕获空白条目。我在属性上方添加了Required DataAnnotation,希望当我尝试更新值时它会捕捉到这一点。但是,当我更新它时,它只是将属性设置为 null 并继续没有任何问题。 我还尝试了 [RegularExpression] 和 [StringLength] 验证属性,但这些也只是被绕过了。
模型:
public class CaseDescriptionModel
{
public int CaseId { get; set; }
[Display(Name = "Description:")]
[Required]
public string CaseDescription { get; set; }
public CaseDescriptionModel() { }
public CaseDescriptionModel(Case case)
{
if (case == null)
{
throw new ArgumentNullException("case");
}
CaseId = case.ID;
CaseDescription = case.Description;
}
}
观点:
@model Models.CaseDescriptionModel
@{
Layout = null;
}
<div>
@Html.StandardForm(this, "", false, true, "UpdateDescription", "Case",
@<div>
@Html.HiddenFor(m => m.CaseId)
<table class="full-width">
<tbody>
<tr>
<td class="ColumnOneStyle">
@Html.LabelFor(m => m.CaseDescription)
</td>
<td class="ColumnTwoStyle" style="float:right;">
@Html.TextBoxFor(m => m.CaseDescription)
</td>
</tr>
</tbody>
</table>
@Html.ValidationSummary(false, "", new { @class = "" })
<table style="float: right;">
<tr>
<td>
@item.Submit("SUBMIT")
</td>
<td>
@Html.ButtonLinkAction("btnCancel", "CANCEL", "Return to case", "Details", "Case", "btnSecondary", new { id = Model.CaseId })
</td>
</tr>
</table>
</div>
)
</div>
控制器方法
public ActionResult UpdateCase(CaseDescriptionModel model)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
var case= DAL.GetCase(model.CaseId);
DAL.UpdateCaseDescription(model.CaseId, model.CaseDescription);
return RedirectToAction("Details", new { id = model.CaseId });
}
【问题讨论】:
-
你有没有
ModelState.IsValid检查你的控制器方法来验证模型是否有效? -
@Borka 我添加了控制器方法,我需要在哪里添加检查?
标签: c# asp.net-mvc data-annotations