2012-01-05 17 views
4

私はMVC 3で2つのドロップダウンリストを必要とするビューを作成しようとしています。私の唯一の他のMVCアプリケーションでは、Ajaxメソッドを使ってデータを取り込むTelerikコントロールを使用しました。今はこのプロジェクトではサードパーティ製のコントロールを使用しないため、MVC SelectListをドロップダウンに使用します。私はSelectListのデータを取り込む方法について多くの記事を読んできましたが、それらのどれも同じことを二度は言わず、モデルを作成するためには常に別の方法があります。ViewDataまたはViewBagを使用してコレクションを保持し、 ..一貫性がない。MVCのリストをモデルでポストバックで選択する方法は?

ViewDataではなく、モデル自体をデータに使用するMVCビューでドロップダウンを設定するには、最も受け入れられる方法は何ですか?ユーザーがリストから選択してサブミットし、HttpPostアクションが呼び出されると、selectリストプロパティのModelプロパティから選択した値にアクセスするにはどうすればよいですか?

これは私の現在のモデルである:

public class TemporaryRegistration { 
    [Required] 
    [Email(ErrorMessage = "Please enter a valid email address.")] 
    [Display(Name = "Email address")] 
    public string Email { get; set; } 

    [Required] 
    [Integer] 
    [Min(1, ErrorMessage = "Please select an entity type.")] 
    [Display(Name = "Entity Type")] 
    public IEnumerable<SelectListItem> EntityType { get; set; } 

    [Required] 
    [Integer] 
    [Min(1, ErrorMessage = "Please select an associated entity.")] 
    [Display(Name = "Associated Entity")] 
    public IEnumerable<SelectListItem> AssociatedEntity { get; set; } 
} 

これは私の現在のビューである私は、ドロップダウンを使用する必要がある場合には、それだけで私はドロップダウンにそれらを回すか、どのようにTextBoxForを使用していますか?

@model Web.Models.TemporaryRegistration 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
    <legend>Create New ELM Select User</legend> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.Email) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Email) 
      @Html.ValidationMessageFor(model => model.Email) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.EntityType) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.EntityType) 
      @Html.ValidationMessageFor(model => model.EntityType) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.AssociatedEntity) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.AssociatedEntity) 
      @Html.ValidationMessageFor(model => model.AssociatedEntity) 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

これが私の現在のポストのアクションです: はどのようにして、選択した値を得るのですか?

[HttpPost] 
public ActionResult CreateUser(TemporaryRegistration registrationModel) { 
    string newRegistrationGUID = string.Empty; 
    if (!ModelState.IsValid) { 
     return View(); 
    } 

    TemporaryRegistrationEntity temporaryRegistration = null; 
    temporaryRegistration = new TemporaryRegistrationEntity(registrationModel.Email, registrationModel.EntityType, registrationModel.AssociatedEntity); 
    newRegistrationGUID = temporaryRegistration.Save(); 
    return Content("New registration was created with GUID " + newRegistrationGUID); 
} 

答えて

8

のは、あなたがToyと呼ばれるモデルを持っているとしましょう...コメントから

を継続。玩具はNamePrice、およびCategoryのような性質を持っています

public class Toy() 
{ 
    public string Name; 
    public double Price; 
    public string Category 
} 

は今、あなたはToyを追加するためのフォームビューを構築したい、と人々は可能性のドロップダウンからカテゴリを選択できるようにする必要があります...何らかの理由でViewDataまたはViewBagでこれをやりたいとは思わない。今

public class ToyViewModel() 
{ 
    public string Name; 
    public double Price; 
    public string Category 

    public ICollection<string> Categories; 
} 

あなた:

代わりのビューにモデルを渡し、NamePriceCategoryを持っているToyViewModelを作成...だけでなく、は、ドロップダウンを移入するカテゴリのコレクションを持っていますコントローラは、この処理を行います。

public ActionResult GetToyForm() 
{ 
    var viewModel = new ToyViewModel(); 
    viewModel.Categories = _service.GetListOfCategories(); 
    return View(viewModel); 
} 

あなたのビューはViewModelににバインドされ、そしてあなたがを使用します210のコレクションをドロップダウンに入力します。あなたはそれを送信すると

@Html.DropDownListFor(model => model.Category, model.Categories) 

、お使いのコントローラのようなものが行われます:それはのようなものになるはずです

[HttpPost] 
public ActionResult CreateToy(ToyViewModel _viewModel) 
{ 
    var model = new Toy(); 
    model.Name = _viewModel.Name 
    // etc. 

    _service.CreateToy(model); 

    // return whatever you like. 
    return View(); 
} 

をあなたがそれらを合わせることができるようにビューへの結合のためのviewmodelsを作るために良い方法ですあなたのモデルをデータレイヤーとビジネスロジックの近くに置いたまま、プレゼンテーションレイヤーのニーズを満たすことができます。

+0

明確化のおかげで、それはまさに私が使っているアーキテクチャのタイプです。要件は実際には、PostModelから変換されたBusiness EntityモデルであるViewModelと、軽量ネットワークトラフィック用のDTOの3つのモデルを使用しています。 –

+1

@ one.beat.consumer私はこれが元の投稿とどのように異なるのか見当たりません。元の投稿のビューモデルは 'TemporaryRegistration'で、エンティティ/パーシスタンスモデルは' TemporaryRegistrationEntity'です。この回答の原文との唯一の違いは、メタデータを除外し、私が使用していたカテゴリを含む**正確な**同じパターンを使用していることです。これは質問の内容でした... –

+0

ありがとう、あなたは一緒に私が全体像を見るのを助け、私はそれを正しい方法でやっているように見えます。 TemporaryRegistrationEnitityは本当に私のビジネスモデルですが、TemporaryRegistrationは単なるビューモデルです。わかりやすくするため、TemporaryRegistrationViewModelに名前を変更します。 –

2

EntityTypeは、あなたが(送信し、リストボックスなど)複数の値を受け入れている場合を除き、リストをする必要はありません。ビューでドロップダウンリスト(通常は単一の値のみを選択する)を表示するときは、ビューモデルの別のプロパティにリストを送信するなど、いくつかの方法で選択肢を提供する必要があります。

public class TemporaryRegistration { 
     [Required] 
     [Email(ErrorMessage = "Please enter a valid email address.")] 
     [Display(Name = "Email address")] 
     public string Email { get; set; } 

     [Required] 
     [Integer] 
     [Min(1, ErrorMessage = "Please select an entity type.")] 
     [Display(Name = "Entity Type")] 
     public int EntityType { get; set; } 

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

     [Required] 
     [Integer] 
     [Min(1, ErrorMessage = "Please select an associated entity.")] 
     [Display(Name = "Associated Entity")] 
     public IEnumerable<SelectListItem> AssociatedEntity { get; set; } 
} 

次に、ドロップダウンリストヘルパーを使用します。

@Html.DropDownListFor(model => model.EntityType, model.EntityTypes) 
+2

私がポストバックすると、モデルのEntityTypeがEntityTypesの選択された値に設定されることを意味すると仮定していますか?そして、私のコントローラ上のGetメソッドアクションでは、新しいviewmodelをインスタンス化し、EntityTypesのコレクションを取得し、それらをmyModel.EntityTypesの値として設定してビューに渡すだけでよいと仮定します。 –

+0

@CDSmithはい正しいです。 –

+0

素晴らしい、ありがとう! –

関連する問題