Bind Data to dropdown in MVC and Entity Framework

2019-09-06 14:52发布

问题:

As of now, dropdown is like this. I want to populate options from database instead of typing. How to do this ? We are using Kendo UI.

<td>
<label  for="ln"  class="lblTask">Type</label><br />
<select name="type" data-bind="value:type" style="color:black">
  <option>CM</option>
  <option>CTA</option>
  <option>ESP</option>
</select>
</td>

回答1:

try this:

In view

 @Html.DropDownListFor(a => a.SelectedItem , Model.Item)

In Model

 public class Items
{

    List<SelectListItem> itemList = new List<SelectListItem>();

    public List<SelectListItem> item
    {
        get { return itemList; }
        set { itemList = value; }
    }



    public items()
    {
        itemList.Add(new SelectListItem() { Value = "1", Text = "CM", Selected = true });
        itemList.Add(new SelectListItem() { Value = "2", Text = "CTA" });
       itemList.Add(new SelectListItem() { Value = "3", Text = "ESP" });


    }

}

Let me know.If it helps.



回答2:

 <input id="type" style="color:black" />


    <script>
    $(document).ready(function() {
                    $("#type").kendoDropDownList({
                        dataTextField: "Name",
                        dataValueField: "Value",
                        dataSource: {
                            transport: {
                                read: {
                                    dataType: "json",
                                    url:'<%=Url.Content("~/Controller/Action")%>',
                                }
                            }
                        }
                    });
                });
    </script>

Considering that your action return jason value as

[{ name: "CM", value: 1 },{ name: "CTA", value: 2 },{ name: "ESP", value: 3 }]

in Controller

public JsonResult ActionName()
            {

                var List= ...
                return Json(List); 
            }

i hope this will help you