簡體   English   中英

ASP.NET MVC 模型將單獨的日、月、年字符串字段綁定到單個 DateTime 對象

[英]ASP.NET MVC Model bindING separate day, month, year string fields to single DateTime object

我目前正在構建一個表單,要求用戶輸入他們的出生日期。 我已經確定最用戶友好的方法是通過單獨的日期日、月和年輸入字段。

我有一個強類型視圖,其中包含生日、出生月份和出生年份的文本框。 將表單發布到服務器后,我需要將這些發布的字符串值轉換為適當的 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 對象會使用發布的出生日期、出生月份、出生年份表單值自動構建?

使用自定義模型綁定器:

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM