![](/img/trans.png)
[英]How can I create nice-looking, functional overlays like what's being used in SharePoint 2010 in ASP.NET MVC?
[英]Asp.Net MVC: How to make validation messages be more nice-looking by default in case of invalid convertion
我有以下模型课:
public class Person{
public int Age { get; set; }
}
并具有以下控制器对其进行编辑:
public class HomeController : Controller
{
...
[HttpPost]
public ActionResult EditPerson(Person person)
{
//... bla bla bla
return View(person);
}
}
提交表单时将调用EditPerson。 该表单包含一个名为“年龄”的输入。 如果用户输入非数字字符串-调用EditPerson时,ModelState [“ Info”]包含诸如“值'0dfrg'对Age无效”之类的错误。
我调查了MS源,发现如果任何类型转换都失败,则会设置此类错误消息。 但在上述情况下,我想写些类似“字段'年龄'必须包含数字”之类的东西。 如果无法将字符串转换为整数,是否可以使MVC以这种方式起作用? (并且还为其他类型(例如日期)提供了相同的错误消息)
Upd:我想找到一种方法来在发生转换错误的情况下能够显示漂亮的默认错误消息,从而不必担心每个特定的属性(此问题的标题也已更改)
您可以使用验证属性,并将其放在这样的模型字段中
public class Person{
[RegularExpression(@"[0-9]*$", ErrorMessage = "Field 'Age' must contain a number")]
public int Age { get; set; }
}
这比仅在操作中执行验证要好,在这种情况下,还将添加客户端验证。
确保在视图中使用html helper来显示验证。 在这种情况下,
@Html.TextBoxFor(model => model .Age)
@Html.ValidationMessageFor(model => model.Age)
看看是否有帮助
[RegularExpression(@"\d+", ErrorMessage = "Field 'Age' must contain a number")]
public int Age { get; set; }
感谢您的解决方案,但是我要为模型可以包含的每个int,datetime等字段做出正确的行为。 这样我就不必为这些事情而烦恼。 我找到了解决方案(由于可以调试MS代码)。 这很丑陋,但是可以工作:
1)在Application_Start插入行中:
ModelBinders.Binders.DefaultBinder =新的ExtendedModelBinder();
2)定义ExtendedModelBinder类:
public class ExtendedModelBinder : DefaultModelBinder
{
string GetErrorMessageForType(Type type)
{
if (type == typeof(int))
return "You must enter an integer numeric value";
if (type == typeof(double))
return "You must enter a numeric value";
return "The entered value is incorrect";
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object res = base.BindModel(controllerContext, bindingContext);
foreach (var entry in bindingContext.ModelState)
{
if (entry.Value.Errors != null)
{
var itemsToReplace = new List<ModelError>();
foreach (var err in entry.Value.Errors)
{
if (string.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null)
{
var ex = err.Exception;
while (!(ex is FormatException) && ex != null)
ex = ex.InnerException;
if (ex != null)
{
itemsToReplace.Add(err);
}
}
}
foreach (var err in itemsToReplace)
{
var ex = err.Exception;
entry.Value.Errors.Remove(err);
entry.Value.Errors.Add(GetErrorMessageForType(bindingContext.ModelType));
}
}
}
return res;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.