Bind Data to dropdown in MVC and Entity Framework

梦想的初衷 提交于 2019-12-25 05:14:11

问题


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



来源:https://stackoverflow.com/questions/24744471/bind-data-to-dropdown-in-mvc-and-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!