标签: selectlistitem

如何将枚举转换为List <SelectListItem>?

我有一个asp.net-mvc网页,我想显示一个基于枚举的下拉列表.我想显示每个枚举项的文本,id是与枚举关联的int值.有没有优雅的方式进行这种转换?

c# asp.net-mvc enums selectlistitem

63
推荐指数
4
解决办法
4万
查看次数

具有下拉列表的Asp.Net MVC和SelectListItem协助

我正在尝试构建一个Dropdownlist,但与Html.DropDownList渲染作斗争.

我有一节课:

public class AccountTransactionView
{
    public IEnumerable<SelectListItem> Accounts { get; set; }
    public int SelectedAccountId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这基本上是我现在的视图模型.帐户列表以及用于返回所选项目的属性.

在我的控制器中,我像这样准备好数据:

public ActionResult AccountTransaction(AccountTransactionView model)
{
    List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);

    AccountTransactionView v = new AccountTransactionView
    {
        Accounts = (from a in accounts
                    select new SelectListItem
                    {
                        Text = a.Description,
                        Value = a.AccountId.ToString(),
                        Selected = false
                    }),
    };

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是:

我正在尝试在我的视图中构建Drop:

<%=Html.DropDownList("SelectedAccountId", Model.Accounts) %>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

具有键"SelectedAccountId"的ViewData项的类型为"System.Int32",但必须是"IEnumerable"类型.

为什么要我退回整个项目清单?我只想要选中的值.我该怎么做?

c# asp.net-mvc selectlistitem

14
推荐指数
2
解决办法
11万
查看次数

多选列表未使用linq2sql显示c#mvc中的选定项目

我已经尝试了许多不同的方法将所选项目传递到多选列表而没有运气.最后,我尝试了这个,我认为应该显示所有选中的项目,但仍然没有选择列表中的任何内容.

public MultiSelectList Companies { get; private set; }

Companies = MulitSelectList(subcontractRepository.SubcontractCompanies(Subcontract.subcontract_id), "Value", "Text");
Run Code Online (Sandbox Code Playgroud)

在SubcontractRepository.cs中:

public IEnumerable<SelectListItem> SubcontractCompanies(Guid id)
{
     return c in db.companies
     select new SelectListItem
     {
          Text = c.company_name,
          Value = c.company_id.ToString(),
          Selected = true
     }
}
Run Code Online (Sandbox Code Playgroud)

在视图中:

<p>
    <label for="Companies">Company:</label>
    <%= Html.ListBox("Companies", Model.Companies) %>
    <%= Html.ValidationMessage("Companies", "*") %>
</p>
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc multi-select selectlistitem linq-to-sql

8
推荐指数
1
解决办法
8409
查看次数

ASP.NET MVC DropDownListFor不支持SelectListItem.Selected

DropDownListFor用来在视图中呈现下拉列表.不知怎的,呈现的列表将不会选择SelectListItemSelected设置为true.

在控制器动作中:

var selectList = sortedEntries.Select(entry => new SelectListItem
                            {
                                Selected = entry.Value.Equals(selectedValue),
                                Text = entry.Value,
                                Value = entry.Id
                            });

return View(new DropDownListModel
            {
                ListId = id,
                SelectList = selectList,
                OptionLabel = "Click to Select"
            });
Run Code Online (Sandbox Code Playgroud)

在视图中:

<%= Html.DropDownListFor(m => m.ListId, 
    Model.SelectList, 
    Model.OptionLabel, 
    new {@class="someClass"}) %>
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

  1. 确保Selected设置为只有一个且只有一个项目true.
  2. 删除选项标签参数.
  3. 删除HTML属性对象.
  4. 使用SelectListDropDownListFor:

   Html.DropDownListFor(m => m.ListId, 
        new SelectList(Model.SelectList, "Value", "Text", 
             new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)), 
        new {@class="someClass"}) …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc selectlist selectlistitem html.dropdownlistfor drop-down-menu

7
推荐指数
3
解决办法
8001
查看次数

通过ViewData为DropDownList提供SelectList的强类型视图:提交时类型不匹配

我试图在ASP.NET MVC2 RC 2中创建一个基于日历事件对象的表单.该对象有eventTypeId,它是我需要通过选择列表填充的System.Int32.

用于创建初始视图的控制器是:

[WAuthorize]
public ActionResult AddCalendarEvent()
{
    CalendarEventTypesManager calendarEventTypesManager = 
        new CalendarEventTypesManager();

    ViewData["eventTypeId"] = new SelectList(
        calendarEventTypesManager.SelectAll(), "Id", "Type");

    return View();
}
Run Code Online (Sandbox Code Playgroud)

View的片段(带标题)是:

<%@ Page Title="" Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Extranet.master"
    Inherits="System.Web.Mvc.ViewPage<SomeProject.Models.CalendarEvent>" %>

...

<p><%= Html.DropDownList("eventTypeId") %></p>
Run Code Online (Sandbox Code Playgroud)

哪个结果的HTML:

<p>
<select id="eventTypeId" name="eventTypeId">
    <option value="1">All school activities</option> 
    <option value="2">All school event</option> 
</select>
</p> 
Run Code Online (Sandbox Code Playgroud)

POST接受控制器是:

[WAuthorize]
// TODO research some more
[ValidateInput(false)]              
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult AddCalendarEvent(CalendarEvent newEvent)
{
    ...
Run Code Online (Sandbox Code Playgroud)

(我尝试[Bind (Exclude="eventTypeId")]在"CalendarEvent newEvent"参数前面添加,但它不会改变行为.)

问题:当我提交表单时,我收到一个InvalidOperationException异常:

具有键'eventTypeId'的ViewData项的类型为'System.Int32',但必须是'IEnumerable <SelectListItem>'类型.

我在这里和MVC博客上看了很多例子,但到目前为止还不清楚它应该如何工作(看起来基于很多例子,它应该按原样运行).我是否需要创建第二个具有SelectListItem类型变量的模型来接受SelectListItem并将值转换为System.Int32以实际设置eventTypeId?这似乎相当圆润.

asp.net-mvc post selectlist selectlistitem drop-down-menu

5
推荐指数
1
解决办法
7254
查看次数

如何编写C#Extension方法将Domain Model对象转换为Interface对象?

当您有一个需要显示为接口控件的域对象时,如下拉列表,ifwdev建议创建一个扩展方法来添加.ToSelectList().

原始对象是具有与下拉列表的.Text和.Value属性相同的属性的对象列表.基本上,它是SelectList对象的List,而不是同一个类名.

我想你可以使用反射将域对象转换为接口对象.任何人对C#代码都有任何建议吗?SelectList是SelectListItem的MVC下拉列表.

当然,想法是在视图中做这样的事情:

<%= Html.DropDownList("City", 
         (IEnumerable<SelectListItem>) ViewData["Cities"].ToSelectList() )
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc domain-driven-design selectlist selectlistitem

5
推荐指数
1
解决办法
2237
查看次数

SelectListItem /更新应用程序表单MVC3 4.0到MVC5 4.5.1 /视图扩展方法

我在我的MVC3(aspx)中使用了以下内容.NETFramework 4.0非常有用.

查看页面扩展方法:

public static List<SelectListItem> GetDropDownListItems<T>(this ViewPage<T> viewPage, string listName, int? currentValue, bool addBlank)
        where T : class
    {
        List<SelectListItem> list = new List<SelectListItem>();
        IEnumerable<KeyValuePair<int, string>> pairs = viewPage.ViewData[listName] as IEnumerable<KeyValuePair<int, string>>;

        if (addBlank)
        {
            SelectListItem emptyItem = new SelectListItem();
            list.Add(emptyItem);
        }

        foreach (KeyValuePair<int, string> pair in pairs)
        {
            SelectListItem item = new SelectListItem();
            item.Text = pair.Value;
            item.Value = pair.Key.ToString();
            item.Selected = pair.Key == currentValue;
            list.Add(item);
        }
        return list;
    }
Run Code Online (Sandbox Code Playgroud)

部分型号:

public static Dictionary<int, string> DoYouSmokeNowValues = new Dictionary<int, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc extension-methods selectlistitem

5
推荐指数
1
解决办法
333
查看次数

从SelectList获取第N项

我正在尝试对返回SelectList的函数进行单元测试.

如何从SelectList中检索项目以验证我的模型是否正确构造?

mySelectList.Items.First().DataValue

管他呢.

linq ienumerable selectlist selectlistitem c#-4.0

4
推荐指数
1
解决办法
2250
查看次数

Asp.net mvc选择列表

我需要创建一个选择列表,保留状态,这不是传递给视图的模型的一部分.我想我应该使用ViewBag将List传递给View?有关实现的任何建议以及如何保留选择列表的状态(如何将选定的值再次传递给操作和视图(可能的方法)?

截至目前的行动:

public ActionResult Images(string x, string y)
{
//some code 

ContentPage cp = this.ContentPage;

return View(cp);
} 

//Post to action with same name:
[HttpPost]
public ActionResult Images(string someParameter)
 {

    ContentPage cp = this.ContentPage;

    return View(cp);
 }
Run Code Online (Sandbox Code Playgroud)

截至目前的观点:

@model ContentPage
@{
ViewBag.Title = "Images";
CmsBaseController controller = (this.ViewContext.Controller as CmsBaseController);
}
@using (Html.BeginForm())
{ 
<div>

//This should go to List<SelectListItem> as I understand
<select name="perpage" id="perpage" onchange='submit();'>
           <option value="1">1</option>
           <option value="2">2</option>
           <option value="3">3</option>

</select>
</div>
}
Run Code Online (Sandbox Code Playgroud)

谢谢!!!

asp.net-mvc selectlist selectlistitem asp.net-mvc-3

3
推荐指数
1
解决办法
2万
查看次数

没有ListItems的MVC列表框

我正在尝试显示2个列表框,其中一个具有所有可能的选择,其他将填充用户选择他们的选择但由于某种原因我无法添加空列表框.

这是代码:

@Html.ListBox("somename")
Run Code Online (Sandbox Code Playgroud)

我的错误是:没有类型为'IEnumerable'的ViewData项具有键'somename'.

我用以下代码替换上面的代码行然后它工作正常但我想要一个空的列表框:

@Html.ListBox("somename", liMyList)
Run Code Online (Sandbox Code Playgroud)

其中liMyList是SelectListItem.

是否有可能在MVC中有一个空的列表框?请帮忙

c# listbox selectlistitem asp.net-mvc-4

3
推荐指数
1
解决办法
8369
查看次数

MVC List&lt;SelectListItem&gt; 与组为每个项目创建 optgroup

我遇到了一个问题,我正在创建一个List<SelectListItem>withoptgroups但不是创建optgroup每个组,SelectListItem而是创建一个新的SelectListGroupper SelectListItem。这让我有点困惑,因为SelectListGroup我的代码中没有任何重复的's。

下面是一个例子:

预期结果:

<select datatag="data-States=''" class="form-control filter-select" data-multi-select="" id="States" multiple="multiple" name="States">
    <optgroup label="MA">
    <option value="01602">01602</option>
    <option value="02743">02743</option>
    <option value="01107">01107</option>
    </optgroup>
    </select>
Run Code Online (Sandbox Code Playgroud)

实际结果:

<select datatag="data-States=''" class="form-control filter-select" data-multi-select="" id="States" multiple="multiple" name="States">
<optgroup label="MA">
<option value="01602">01602</option>
</optgroup>
<optgroup label="MA">
<option value="02743">02743</option>
</optgroup>
<optgroup label="MA">
<option value="01107">01107</option>
</optgroup>
</select>
Run Code Online (Sandbox Code Playgroud)

方法:

 public ManifestFilterDropDownItem ReturnManifestFilterDataBasedOnTotalDataSet(IEnumerable<ManifestTableItem> data, bool isUserASR) {
            IEnumerable<SelectListGroup> stateGroups = data.Select(x => x.AddrState.ToUpper()).Distinct().Select(x => new SelectListGroup() {
                Name = …
Run Code Online (Sandbox Code Playgroud)

html c# asp.net-mvc selectlistitem

3
推荐指数
1
解决办法
6330
查看次数

添加新选择列表项的对象引用错误

我遇到了问题List<SelectListItem>.只要代码命中foreach它就说:

object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

我错过了什么,或者任何人都可以解释为什么它会失败?

public ActionResult HammerpointVideos(string category, string type)
{
    var stuff = Request.QueryString["category"];

    var ItemId = (from p in entities.EstimateItems
                  where p.ItemName == category
                  select p.EstimateItemId).FirstOrDefault();

    var Videos = (from e in entities.EstimateVideos
                  where e.EstimateItemId == ItemId
                  select new Models.HammerpointVideoModel
                  {
                      VideoName = e.VideoName,
                      VideoLink = e.VideoLink
                  }).ToList();

    var model= new Models.HammerpointVideoListModel();
    List<SelectListItem> list = model.VideoList;

    foreach (var video in Videos)
    {
        list.Add(new SelectListItem()
                    {
                        Selected=false, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc list selectlistitem

1
推荐指数
1
解决办法
2228
查看次数

具有布尔值而不是字符串的SelectListItem

无法将SelectListItem.Value属性从转换stringBoolean。如何创建一个简单的是/与价值无选项true/ false

private List<SelectListItem> getYNOptions()
        {
            List<SelectListItem> yn = new List<SelectListItem>();
            yn.Add(new SelectListItem() { 
                Text = "Yes",
                Value=true, // error
                Selected = false
            });
            yn.Add(new SelectListItem()
            {
                Text= "No",
                Value = false, // error
                Selected = false
            });
            return yn;
        } 

public ActionResult Index(){
    ViewBag.selectList = getYNOptions();
    return View();
}
Run Code Online (Sandbox Code Playgroud)

视图

 @Html.DropDownListFor(model => model.YesOrNo, new SelectList(ViewBag.selectList,"Value","Text"), "-- Select --")
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc selectlist selectlistitem html.dropdownlistfor

0
推荐指数
1
解决办法
3612
查看次数