【发布时间】:2013-12-20 23:39:26
【问题描述】:
在了解了所有示例和教程等之后,我正在尝试将 MVC 用于一个新项目。但是,我很难确定某些事情应该在哪里发生。
例如,我有一个名为 Profile 的实体。此实体包含正常的配置文件类型内容以及 DateTime 类型的 DateOfBirth 属性。在 HTML 表单中,出生日期字段分为 3 个字段。现在,我知道我可以使用自定义模型绑定器来处理这个问题,但是如果输入的日期不是有效日期怎么办?我应该在模型活页夹中检查吗?我的所有验证都应该放在模型活页夹中吗?是否可以只在模型绑定器中验证少数内容,而在控制器或模型本身中验证其余内容?
这是我现在拥有的代码,但它对我来说看起来不正确。看起来又脏又臭。
namespace WebSite.Models
{
public class ProfileModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
DateTime birthDate;
var form = controllerContext.HttpContext.Request.Form;
var state = controllerContext.Controller.ViewData.ModelState;
var profile = new Profile();
profile.FirstName = form["FirstName"];
profile.LastName = form["LastName"];
profile.Address = form["Address"];
profile.Address2 = form["Address2"];
profile.City = form["City"];
profile.State = form["State"];
profile.Zip = form["Zip"];
profile.Phone = form["Phone"];
profile.Email = form["Email"];
profile.Created = DateTime.UtcNow;
profile.IpAddress = controllerContext.HttpContext.Request.UserHostAddress;
var dateTemp = string.Format("{0}/{1}/{2}",
form["BirthMonth"], form["BirthDay"], form["BirthYear"]);
if (string.IsNullOrEmpty(dateTemp))
state.AddModelError("BirthDate", "Required");
else if (!DateTime.TryParse(dateTemp, out birthDate))
state.AddModelError("BirthDate", "Invalid");
else
profile.BirthDate = birthDate;
return profile;
}
}
}
基于上面的示例代码,您将如何为 3 部分字段生成验证消息?在上述情况下,我使用了一个完全独立的键,它实际上并不对应于表单中的字段,因为我不希望在所有 3 个字段旁边出现错误消息。我只希望它出现在 Year 字段的右侧。
【问题讨论】:
-
您在寻找模型验证还是表单验证?我会推荐两者。通过这种方式,您可以定制模型并在前端提供丰富的 UI。
标签: asp.net asp.net-mvc