0

単純な形式の DTO オブジェクトを使用する HttpPost コントローラー アクションがあります。

[HttpPost]
public ViewResult Index(ResultQueryForm queryForm)
{
   ...
}

public class ResultQueryForm
{
   public DateTime? TimestampStart { get; set; }
   public DateTime? TimestampEnd { get; set; }
   public string Name { get; set; }
}

DTO オブジェクトには、範囲の作成に使用される null 許容の日時フィールドがあります。nullable に設定されている理由は、モデルにバインドされているフォームがクエリ フォームであり、ユーザーがフォームに日付値を入力する必要がないためです。

私が直面している問題は、ユーザーが無効な日付を入力した場合、MVC の既定のモデル バインディングでエラー メッセージを表示することです。DateTime を受け取るコントローラー アクションがある場合、これは問題なく発生しますか? 引数として入力しますが、DateTime を保持する DTO を渡しているので? モデル バインディングを入力すると、DateTime を設定するだけのように見えますか? 変数を null にします。これにより、予期しない結果が発生します。

ノート:

[HttpPost]
public ViewResult Index(DateTime? startDate)
{
   // If the user enters an invalid date, the controller action won't even be run because   the MVC model binding will fail and return an error message to the user
}

DateTimeをバインドできない場合、MVCモデルバインディングに「失敗」するように指示する方法はありますか? null に設定するのではなく、フォーム DTO オブジェクトに値を設定しますか? より良い方法はありますか?form/dto オブジェクトには大量のプロパティがあるため、個々のフォーム入力をコントローラーに渡すことは不可能です (読みやすくするために、それらの多くを除外しました)。

4

2 に答える 2

1

コントローラー アクションでモデルを検証できます。

if(!Model.IsValid)
{
  return View(); // ooops didn't work
}
else
{
  return RedirectToAction("Index"); //horray
}

もちろん、そこには何でも入れて、ページに表示したい場合は Json オブジェクトを返すことができます。

ValidateInput(true)また、次のようにアクション メソッドの先頭を追加する必要があります。[HttpPost, ValidateInput(true)]

于 2012-01-03T17:48:42.283 に答える
1

このためのカスタム ValidationAttribute を作成できると思います。

[DateTimeFormat(ErrorMessage = "Invalid date format.")]
public DateTime? TimestampStart { get; set; }
[DateTimeFormat(ErrorMessage = "Invalid date format.")]
public DateTime? TimestampEnd { get; set; }


[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DateTimeFormatAttribute : ValidationAttribute
{
    public override bool IsValid(object value) {

        // allow null values
        if (value == null) { return true; }

        // when value is not null, try to convert to a DateTime
        DateTime asDateTime;
        if (DateTime.TryParse(value.ToString(), out asDateTime)) {
            return true; // parsed to datetime successfully
        }
        return false; // value could not be parsed
    }
}
于 2012-01-03T17:50:26.530 に答える