7

MVC3では、データ注釈を使用してUIの開発と検証を高速化できます。すなわち。

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

ただし、モバイルアプリの場合、フィールドラベルはなく、データベースから入力されたドロップダウンリストのみです。これをこのように定義するにはどうすればよいですか?

    [Required]
    [DataType(DataType.[SOME LIST TYPE???])]
    [Display(Name = "")]
    public string Continent { get; set; }

このためにこの方法を使用しない方が良いですか?

4

2 に答える 2

9

このようにViewModelを変更します

public class RegisterViewModel
{
   //Other Properties

   [Required]
   [Display(Name = "Continent")]
   public string SelectedContinent { set; get; }
   public IEnumerable<SelectListItem> Continents{ set; get; }

}

そして、GETActionメソッドで、DBからデータを取得を設定し、ViewModelのContinentsCollectionプロパティを設定します

public ActionResult DoThatStep()
{
  var vm=new RegisterViewModel();
  //The below code is hardcoded for demo. you may replace with DB data.
  vm.Continents= new[]
  {
    new SelectListItem { Value = "1", Text = "Prodcer A" },
    new SelectListItem { Value = "2", Text = "Prodcer B" },
    new SelectListItem { Value = "3", Text = "Prodcer C" }
  }; 
  return View(vm);
}

そしてあなたのViewDoThatStep.cshtml)でこれを使用してください

@model RegisterViewModel
@using(Html.BeginForm())
{
  @Html.ValidationSummary()

  @Html.DropDownListFor(m => m.SelectedContinent, 
               new SelectList(Model.Continents, "Value", "Text"), "Select")

   <input type="submit" />
}

これで、DropDownRequiredフィールドが作成されます。

于 2012-08-17T19:22:09.520 に答える
3

DropDownで要素の選択を強制する[Required]場合は、バインドするフィールドの属性を使用します。

public class MyViewModel
{
    [Required]
    [Display(Name = "")]
    public string Continent { get; set; }

    public IEnumerable<SelectListItem> Continents { get; set; }
}

そしてあなたの見解では:

@Html.DropDownListFor(
    x => x.Continent, 
    Model.Continents, 
    "-- Select a continent --"
)
@Html.ValidationMessageFor(x => x.Continent)
于 2012-08-17T19:22:13.810 に答える