2017-11-20 2 views
-1

나는 Mysql에 정의 테이블을 가지고있다. 너무 쉽습니다. 예 :Override Html.DropDownListFor()

GroupId Name 
1  Colors 
2  Size 

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

나는 DropdownListFor를 사용한다. DropDownList와 같은 사용자 지정 컨트롤을 만들고 싶습니다. 예 :

Html.CustomDropDownList ("sizeId", 2) < --- 2는 크기 그룹입니다.

어떻게 이런 식으로 제어 할 수 있습니까?

끝 부분에는 다음과 같은 내용이 있습니다.

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

당신의 요구 사항이 명확하지 않습니다. 출력을 원하면 무엇입니까? –

+0

그것의 쉬운. DropdownListFor와 같습니다. 반환 옵션 선택 요소입니다 – caras

+0

어떤 옵션이 있습니까? 어떤 html이이 방법을 생성 할 것으로 기대합니까? –

답변

0

사실 매우 쉽습니다.

//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)); 
    } 

그러면 다음과 같이 부를 수 있습니다.

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

해피 코딩!