mvc dropdown option with title tag in mvc

2019-05-31 14:02发布

<select id="priority">
    <option value="calendar" title="icons/icon_calendar.gif">Calendar</option>
    <option value="shopping_cart" title="icons/icon_cart.gif">Shopping Cart</option>
    <option value="cd" title="icons/icon_cd.gif">CD</option>
    <option value="email"  selected="selected" title="icons/icon_email.gif">Email</option>
    <option value="faq" title="icons/icon_faq.gif">FAQ</option>
    <option value="games" title="icons/icon_games.gif">Games</option>
</select>

I want this type of drop down in mvc with title attribute

 @Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { @class = "required" })

3条回答
倾城 Initia
2楼-- · 2019-05-31 14:45

Probably you can achieve your desired output by 1.create a custom helper with with extension method which will return MvcHtmlString which will create your custom HTML for dropdown and call that method in your view.

Like Below

public static class CustomDropdown
{
public static string Dropdown(Priority priority)
      {       
           StringBuilder sb=new StringBuilder ();
           sb+="<Select id='drop'>";
           for(int i=0;i<priority.name.length;i++)
       {
           sb+="<option id='dropop' value='"+priority.value[i]+"'                      title='"+priority.title[i]+"'>"+priority.name[i]+"</option>";
       }
        sb+="</select>";
              return Convert.ToString(sb);                   
      }
   }
 }

2.Bind the options of the given select with help of jquery like

  var i=0;
$('.drpclass option').each(function(){
$(this).attr('title',Model.priority.title[i])
i++;
});
查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-31 14:58

The built-in DropDownList helper doesn't allow you for setting additional HTML attributes on individual options such as title. You will have to write your own custom helper if you want to achieve that. Here's one same implementation you may take a look at adapt to your needs.

查看更多
Rolldiameter
4楼-- · 2019-05-31 15:02
@Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { @class = "required", title="priority" })
查看更多
登录 后发表回答