asp.net-mvc 如何使用默认值创建一个空的下拉列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15640275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:41:47  来源:igfitidea点击:

How to create an empty dropdown list with default value?

asp.net-mvcdrop-down-menu

提问by Hamid Reza

I want to create an empty dropdown list that has just default value.I use the following code:

我想创建一个只有默认值的空下拉列表。我使用以下代码:

@Html.DropDownList("parent","--Select Parent--")

But in running time I see this error:

但在运行时我看到这个错误:

There is no ViewData item of type 'IEnumerable' that has the key 'parent'.

没有键为“父”的“IEnumerable”类型的 ViewData 项。

How can I solve it? Thanks.

我该如何解决?谢谢。

采纳答案by Shyju

You may simply create an HTML Select option in your view.

您可以简单地在您的视图中创建一个 HTML 选择选项。

<select id="parent" name="parent">
   <option value="">Select parent </option>
</select>

EDIT :As per the comment.

编辑:根据评论

When you submit the form, You can get the selected value by either having a parameter with parentname

当您提交表单时,您可以通过具有parent名称的参数来获取所选值

[HttpPost]
public ActionResult Create(string parent,string otherParameterName)
{
  //read and save and return / redirect
}

ORhave a parentproperty in your ViewModel which you are using for Model binding.

或者parent在您的 ViewModel 中有一个用于模型绑定的属性。

public class CreateProject
{
  public string parent { set;get;}
  public string ProjectName { set;get;}
}

and in your action method.

并在您的操作方法中。

[HttpPost]
public ActionResult Create(CreateProject model)
{

  // check model.parent value.
}

回答by stenlytw

You can build an empty DropDownList like this:

您可以像这样构建一个空的 DropDownList:

@Html.DropDownList("parent", Enumerable.Empty<SelectListItem>(), "--Select Parent--")

Reference: Build an empty MVC DropdownListFor for a Cascade Sub-List

参考:为级联子列表构建一个空的 MVC DropdownListFor

回答by Carlos Maia de Morais

Adding html attributes to the above example:

在上面的例子中添加 html 属性:

    @Html.DropDownList("Idparent", Enumerable.Empty<SelectListItem>(), "Select one...", new {@class="form-control"})                 

回答by Syed Raffiuddin

You can do something like this in your controller to build a empty dropdown list

你可以在你的控制器中做这样的事情来建立一个空的下拉列表

    ViewBag.ClassID = new SelectList(db.Classes.Where(c => c.ClassID == 0)  , "ClassID", "ClassName").ToList();