简体   繁体   中英

MVC.NET: define a strongly typed HTML Helper for DropDownList

I am trying to find out how I could define my own HtmlHelper for creating a dropdownlist. I have the following scenarion: I am using the select2 jQuery plugin ( http://ivaynberg.github.io/select2/ ) for multiple selects with search and better interface. My Model has x id's of tags associated. As I understand it, these tags can only get a value when an Html helper like @Html.DropDownListFor() is used? I would like to

  • write pure html and somehow tell it the value has to be stored in the list of tag-id's in my model

    OR

  • make an HTML Helper which can achieve the same effect.

Currently I have this, but I see no way of passing the selected values to the model when the form gets posted:

<div>
        <label>Kies je thema's (maximum 2):</label>
        <select id="select2select" multiple style="width: 500px">
            @foreach (var top in ((List<Topic>)ViewBag.TopIds).Where(top => top.MainTopic == null))
            {
                <option value="@top.TopicId" class="optionGroup">@top.Name</option>
                foreach (var subTopic in top.SubTopics)
                {
                    <option value="@subTopic.TopicId" class="optionChild">@subTopic.Name</option>
                }
            }
        </select>
    </div>

How can I get the selected value in the property in my list while keeping this structure?

Extra: as you can see my options have classes, this is because I have Main tags and subtags. Users can choose either main tags or subtags, so I can't work with <optiongroup> because they 'groups' have to be selectable. I give them, depending on their class, a different format using select2 format.

请尝试以下代码以纠正问题

 @Html.DropDownListFor(m => top.SubTopics, new SelectList(top.SubTopics, "TopicId", "Name"))

There is a couple of ways you can do this.

@Html.DropDownListFor(m => top.SubTopics, new SelectList(top.SubTopics, "TopicId", "Name"))

@Html.DropDownListFor(m => Model.SubTopics, Model.SubTopics, null, htmlAttributes: new { @class = "ui search selection dropdown clearable", @clearable = "", @id = "Model_SubTopics" })

These two can have issues with changing html Attribute "name" values for different model binding.

you can use a Tag Helper to do it the more modern way.

<select asp-for="Model.SubTopics" asp-items="@Model.SubTopics"  class="ui search selection dropdown clearable" ></select>

This way will take the pre-configured value if you have model binding for the input form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM