2017-11-20 6 views
-1

Ich habe eine Definitionstabelle in Mysql. Es ist so einfach, für. BeispielOverride Html.DropDownListFor()

GroupId Name 
1  Colors 
2  Size 

DefinitionId GroupId Name 
1   1  Black 
2   1  Green 
3   2  S 
4   2  M 

Ich benutze DropDownListFor. Ich möchte ein benutzerdefiniertes Steuerelement wie DropDownList erstellen. ForBeispiel:

Html.CustomDropDownList ("sizeId", 2) < --- 2 ist Gruppe der Größe.

Wie kann ich Kontrolle so erstellen.

Am Ende ist wieder so etwas zu haben.

<select Id="sizeId" name="sizeId"> 
    <option value="3">M</option> 
    <option value="4">S</option> 
</selec> 
+0

Nicht klar, was Sie fragen. Wonach möchtest du die Ausgabe? –

+0

Es ist einfach. Wie DropDownListFor. Es wird Return-Option Elemente – caras

+0

Welche Optionen? Welchen HTML-Code erwarten Sie von dieser Methode? –

Antwort

0

Eigentlich ist es so einfach.

//This overload is extension method accepts name, list and htmlAttributes as parameters. 
    public static MvcHtmlString DefinitionFor(this HtmlHelper helper, string name, int GroupId, object htmlAttributes) 
    { 
     // ref to db 

     var db = (Service.Interfaces.ISet<Definition>) 
     DependencyResolver.Current.GetService(typeof(Interfaces.ISet<Definition>)); 

     //Creating a select element using TagBuilder class which will create a dropdown. 
     TagBuilder dropdown = new TagBuilder("select"); 
     //Setting the name and id attribute with name parameter passed to this method. 
     dropdown.Attributes.Add("Key", name); 
     dropdown.Attributes.Add("Id", name); 

     //Created StringBuilder object to store option data fetched oen by one from list. 
     StringBuilder options = new StringBuilder(); 
     //Get Item(s) 
     var items = db.Get(new Definition() { Group = new Group() { Id = GroupId } }).List; 
     foreach (var item in items) 
     { 
      //Each option represents a value in dropdown. For each element in the list, option element is created and appended to the stringBuilder object. 
      options = options.Append("<option value='" + item.Id + "'>" + item.Key + "</option>"); 
     } 
     //assigned all the options to the dropdown using innerHTML property. 
     dropdown.InnerHtml = options.ToString(); 
     //Assigning the attributes passed as a htmlAttributes object. 
     dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 
     //Returning the entire select or dropdown control in HTMLString format. 
     return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal)); 
    } 

Dann kann ich so anrufen.

<div> 
    @Html.DefinitionFor("colorId", 2, new { @class = "form-control" }); 
</div> 

Glückliche Codierung!