2

現在、ユーザーが生年月日を入力する必要があるフォームを作成しています。これを行うための最もユーザー フレンドリーな方法は、日、月、および年の個別の入力フィールドを使用することであると判断しました。

誕生日、誕生月、誕生年のテキスト ボックスを含む、厳密に型指定されたビューがあります。フォームがサーバーにポストされたら、これらのポストされた文字列値を適切な 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 オブジェクトが自動的に構築されるようにする方法はありますか?

4

1 に答える 1

1

カスタム モデル バインダーを使用します。

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();
}
于 2016-03-23T10:15:15.920 に答える