如何使用asp.net mvc从ListBox中的DB填充检索到的值

时间:2013-06-11 10:01:29

标签: asp.net-mvc-3 entity-framework razor

任何人都可以帮我解决如何在ListBoxFor中填充检索到的值。我尝试了这个但是没有用。

模型中的代码: -

public List<SelectListItem> SafetyRepresentataives { get; set; }
public List<string> BusinessUnitSiteSafetyRepresentative { get; set; }

Controller中的代码:=

var site = entityDB.ClientBusinessUnitSites.FirstOrDefault(m => m.ClientBusinessUnitSiteId == 
siteId);
var siteRepresentatives = from representatives in entityDB.ClientBusinessUnitSiteRepresentatives
                                      where representatives.ClientBUSiteID == siteId
                                      select representatives;

local.SafetyRepresentataives = (from o in entityDB.SystemUsersOrganizations.ToList()
                                           from c in entityDB.Contact.ToList()
                                           where o.OrganizationId == clientId && c.UserId == 
                                            o.UserId
                                           select new SelectListItem
                                           {
                                               Text = c.FirstName + "," + c.LastName,
                                               Value = c.UserId.ToString()
                                           }).ToList();
foreach (var representative in siteRepresentatives)
            {   
local.BusinessUnitSiteSafetyRepresentative.Add(representative.SafetyRepresentative.ToString());
            }

视图中的代码: -

@Html.ListBoxFor(x => Model.BusinessUnitSiteSafetyRepresentative, new 
MultiSelectList(Model.SafetyRepresentataives,"Value","Text"))

我已从DB中检索了值,如上所示。但是我无法将这些检索到的值链接到ListBox以便填充它们。这该怎么做??请帮帮我!!!!!!!!!

2 个答案:

答案 0 :(得分:0)

我认为此链接可以帮助您

http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

在样本中,他们传递了视图包中的组合框项目。

我建议您使用jquery插件,例如自动完成或来自twitter bootstrap的typeahead。因此,您可以异步加载元素。

答案 1 :(得分:0)

简单地添加默认列表帮助我解决了我的问题。这是解决方案。

local.BusinessUnitSiteSafetyRepresentative = new List<string>();
            foreach (var representative in siteRepresentatives)
            {

local.BusinessUnitSiteSafetyRepresentative.Add(representative.SafetyRepresentative.ToString());
            }