2011-07-12 12 views
4

コントローラでSelectListを作成してビューに渡すにはどうすればよいですか? " - 選択 - "オプションの値を0にする必要があります。コントローラまたはビューモデルからドロップダウンリストを作成

私はreplies that I got from Jeremey of Fluent Validationに応答しています。

これは私の現在のものです。私のビューモデル:

[Validator(typeof(CreateCategoryViewModelValidator))] 
public class CreateCategoryViewModel 
{ 
    public CreateCategoryViewModel() 
    { 
     IsActive = true; 
    } 

    public string Name { get; set; } 
    public string Description { get; set; } 
    public string MetaKeywords { get; set; } 
    public string MetaDescription { get; set; } 
    public bool IsActive { get; set; } 
    public IList<Category> ParentCategories { get; set; } 
    public int ParentCategoryId { get; set; } 
} 

マイコン。

public ActionResult Create() 
{ 
    List<Category> parentCategoriesList = categoryService.GetParentCategories(); 

    CreateCategoryViewModel createCategoryViewModel = new CreateCategoryViewModel 
    { 
     ParentCategories = parentCategoriesList 
    }; 

    return View(createCategoryViewModel); 
} 

これは私が私の見解で持っているものです。

@Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --") 

はどのようにして、コントローラやビューモデルのドロップダウンリストを作成し、ビューに渡すのですか?

答えて

3

モデルをIList<Category>に変更してください0どこの値を持つオプション「 - - を選択し、」O、その後SelectListと、このようにそれをインスタンス化...

List<ParentCategory> parentCategories = categoryService.GetParentCategories(); 

parentCategories.Insert(0, new ParentCategory(){ Id = "0", Name = "--Select--"}); 

ParentCategories = new SelectList(parentCategories, "Id", "Name"); 

は、その後、あなたのビューでは、単に私が必要

@Html.DropDownListFor(m => m.ParentCategoryId, Model.ParentCategories); 
+0

を呼び出すことができますそれはあなたのコードでこれを述べているのですか? –

+0

申し訳ありませんが、私はそのビットを逃しました。なぜあなたは値0を持つ必要がありますか? – simonlchilds

+0

私はFluent Validationを使用しています。 Jeremyは、値を0にするselectオプションが必要であると言います。そうでないと、ドロップダウンで値を選択しないとModelStateは常にfalseになります。 –

0

私がそれをやったことのある方法は、ドロップダウンアイテムのIDと値をラップするオブジェクトを作成することです(List<SelectValue>のように)。 ViewModelでビューに渡してから、HTMLヘルパーを使用してドロップダウンを構築します。ここで

public class SelectValue 
{ 
    /// <summary> 
    /// Id of the dropdown value 
    /// </summary> 
    public int Id { get; set; } 

    /// <summary> 
    /// Display string for the Dropdown 
    /// </summary> 
    public string DropdownValue { get; set; } 
} 

は、ビューモデルである:ここで

public class TestViewModel 
{ 
    public List<SelectValue> DropDownValues {get; set;} 
} 

はHTMLヘルパーです:

public static SelectList CreateSelectListWithSelectOption(this HtmlHelper helper, List<SelectValue> options, string selectedValue) 
{ 
    var values = (from option in options 
        select new { Id = option.Id.ToString(), Value = option.DropdownValue }).ToList(); 

    values.Insert(0, new { Id = 0, Value = "--Select--" }); 

    return new SelectList(values, "Id", "Value", selectedValue); 
} 

次に、あなたのビューであなたはヘルパーを呼び出す:

@Html.DropDownList("DropDownListName", Html.CreateSelectListWithSelect(Model.DropDownValues, "--Select--")) 
関連する問題