gpt4 book ai didi

c# - @Html.ValidationMessageFor 在我尝试编辑项目时崩溃

转载 作者:太空狗 更新时间:2023-10-29 23:54:08 25 4
gpt4 key购买 nike

为什么我的 @Html.ValidationMessageFo 不工作?当我运行该应用程序时,什么也没有发生,它允许输入所有内容。当我尝试在下面的编辑 View 中编辑项目时,它也会崩溃。我有以下内容:

<div class="editor-label">
@* @Html.LabelFor(model => model.Posted)*@
</div>
<div class="editor-field">
@Html.HiddenFor(model => model.Posted, Model.Posted = DateTime.Now)
@Html.ValidationMessageFor(model => model.sendinghome)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Cartypes)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Cartypes)
@Html.ValidationMessageFor(model => model.Cartypes)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.RegNum)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.RegNum)
@Html.ValidationMessageFor(model => model.RegNum)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Regprice)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Image)
@Html.ValidationMessageFor(model => model.Regprice)
</div>

最佳答案

这是验证的工作原理。

假设您有以下模型:

public class MyModel {
[Required]
public string MyProperty { get; set; }
}

注意 Required属性,它是一个数据注释属性,指定 MyProperty 是必填字段。

MyModel 由以下 View (MyView.cshtml) 使用:

@model MyNamespace.MyModel

@using (Html.BeginForm("MyAction", "MyController")) {
@Html.LabelFor(m => m.MyProperty)
@Html.TextBoxFor(m => m.MyProperty)
@Html.ValidationMessageFor(m => m.MyProperty)

<input type="submit" value="Click me">
}

然后,当此表单被发送到 MyControllerMyAction 操作时,将执行模型验证。您需要做的是检查您的模型是否有效。可以使用 ModelState.IsValid 属性来完成。

[HttpPost]
public ActionResult MyAction(MyModel model) {
if (ModelState.IsValid) {
// save to db, for instance
return RedirectToAction("AnotherAction");
}
// model is not valid
return View("MyView", model);
}

如果验证失败, View 将使用 ModelState 对象中存在的不同错误再次呈现。 ValidationMessageFor 助手将使用和显示这些错误。

关于c# - @Html.ValidationMessageFor 在我尝试编辑项目时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com