我有一个控制器,我将错误(例外)添加到ModelState
。在我尝试通过Html.ValidationMessage()
显示消息的视图中,它不显示消息。任何人都可以帮我这个吗?
控制器:
public ActionResult FooMeth()
{
....
if(cond == false)
{
ModelState.AddModelError("mykey","mymessage");
}
....
return View("fooView",mymodel);
}
查看:
@Html.TextBox("foo")
@Html.ValidationMessage("mykey")
而不是显示" mymessage"它总是空白。任何人都可以告诉我这背后的原因是什么?
答案 0 :(得分:1)
尝试在View中使用ViewModel,然后根据ViewModel属性使用Razor Helper:
@Html.TextBoxFor(m => m.Foo)
@Html.ValidationMessageFor(m => m.Foo)
并将其添加到您的视图中,以便显示验证结果
@Html.ValidationSummary(true)
答案 1 :(得分:0)
我认为最好的选择是使用模型和数据注释。 或使用ViewBag显示错误文本。我也看到你发送了我的模特 视图但尚未宣布。
ViewBag方法:
C#:
using MyProject.Models;
public ActionResult FooMeth(MyModel model)
{
if (cond == false)
{
// If failed, return input data and display error.
ViewBag.ServerReply = "My Message.";
return View(model);
}
// If successful return to black page.
return View();
}
HTML:
@Html.TextBoxFor(m => m.Foo)
@ViewBag.ServerReply
或者您可以将模型验证与数据注释一起使用:
模特&数据注释方法:
using System.ComponentModel.DataAnnotations;
public class MyModel
{
[Required(ErrorMessage = "Please fill in text box.")]
[StringLength(62, ErrorMessage = "Text must be {0} characters or less.")]
public string Foo { get; set; }
}
C#
using MyProject.Models;
public ActionResult FooMeth(MyModel model)
{
if (ModelState.IsValid)
{
// Code here if successful.
}
// If model is not valid return model with error messages.
return View(model);
}
HTML:
@Html.TextBoxFor(m => m.Foo)
@Html.ValidationMessageFor(m => m.Foo)
答案 2 :(得分:0)
如果上述答案在您的情况下不起作用,请尝试这些
1)看看不显眼的js是否正在加载
2)为Ajax.BeginForm和内部表单show @ Html.ValidationSummary或Message