ASP.NET MVC模型将单独的日,月,年字符串字段绑定到单个DateTime对象

CodeMonkey

我目前正在建立一个要求用户输入出生日期的表格。我已经确定,最方便用户使用的方法是通过单独的日期,日期,月份和年份输入字段。

我有一个强类型视图,其中包含生日,出生月份和出生年份的文本框。将表单发布到服务器后,我需要将这些发布的字符串值转换为正确的DateTime对象。我目前正在执行年龄验证测试的自定义验证器中生成此DateTime对象,但是我相信有更好的方法。

到目前为止,我已经尝试如下在模型构造函数中构建DateTime对象:

public class Applicant
{
    [Required(ErrorMessage = "Day Required")]
    public string DobDay { get; set; }
    [Required(ErrorMessage = "Month Required")]
    public string DobMonth { get; set; }
    [Required(ErrorMessage = "Year Required")]
    [BirthDateValidation("DobDay", "DobMonth")]
    public string DobYear { get; set; }

    public DateTime BirthDate { get; set; }

    public Applicant()
    {
        this.BirthDate = new DateTime(Convert.ToInt32(this.DobYear), Convert.ToInt32(this.DobMonth), Convert.ToInt32(this.DobDay));
    }
}

有一种方法可以使该任务更加自动化,就像我在上面尝试过的那样,以便在将表单发布到服务器时使用发布的出生日期,出生月份,出生年份的表单值自动构建DateTime对象?

詹姆斯·戴夫(James Dev)

使用自定义模型活页夹:

public class MyCustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
                            ModelBindingContext bindingContext)
    {
        HttpRequestBase request = controllerContext.HttpContext.Request;

        string day = request.Form.Get("DobDay");
        string month = request.Form.Get("DobMonth");
        string year = request.Form.Get("DobYear");
        //etc..
        return new Applicant
        {
            BirthDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day))
            //etc..
        };
    }
}

[HttpPost]
public ActionResult Save([ModelBinder(typeof(MyCustomBinder))] Applicant applicant)
{
    return View();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将json字符串绑定到asp.net MVC中的模型

查询字符串模型绑定ASP.NET WebApi

Asp.Net核心模型绑定,如何获取空字段以绑定为空白字符串?

如何将查询字符串映射到模型数据ASP.Net MVC

DateTime用户声明,将日期格式设置为字符串(Asp.Net MVC 5)

Asp.Net MVC-模型绑定到模型或ViewModel

无法将字符串数组发布到 ASP.NET MVC3

将HTML字符串从控制器传递到View ASP.Net MVC

复杂的对象和模型绑定器ASP.NET MVC

ASP.NET Core 3 MVC:对象列表的模型绑定

Asp.net- Mvc复杂模型绑定

ASP .NET Core 模型绑定

ASP.NET Core MVC:如何获取原始JSON绑定到没有类型的字符串?

ASP.NET MVC:DropDownList到模型字段

在asp.net mvc 4中回发时未绑定到模型的对象列表

如何使用ASP.NET MVC手动将数据从ModelStateDictionary绑定到表示模型?

ASP.Net Core API 将模型 int Id 绑定到自定义 Id 对象

asp.net mvc 参数绑定字符串和guid

如何不使用表单将字符串数组发布到ASP.NET MVC Controller?

如何将字符串值从 WidowsForm 传递到 ASP.NET MVC 控制器

ASP.NET的连接字符串

与ASP.Net的连接字符串

到 JDBC 的 ASP.NET 连接字符串

ASP.NET连接字符串到SQL Server

将模型对象列表列表发布到ASP.NET MVC中的Controller

验证ASP.NET MVC中的字符串数组

连接字符串的ASP.NET MVC部署问题

通过asp-for =“ ...”将字符串值传递到ASP.Net核心中的模型中的方式不起作用

从View发送字符串到Controller ASP.Net MVC