mvc dropdown option with title tag in mvc

2019-05-31 14:28发布

问题:

<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" })

回答1:

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.



回答2:

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


回答3:

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