如何使用默认值创建一个空的下拉列表?

Ham*_*eza 4 asp.net-mvc drop-down-menu

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

@Html.DropDownList("parent","--Select Parent--")
Run Code Online (Sandbox Code Playgroud)

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

没有类型为'IEnumerable'的ViewData项具有键'parent'.

我该如何解决?谢谢.

ste*_*ytw 15

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

@Html.DropDownList("parent", Enumerable.Empty<SelectListItem>(), "--Select Parent--")
Run Code Online (Sandbox Code Playgroud)

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


小智 7

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

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


Shy*_*yju 5

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

<select id="parent" name="parent">
   <option value="">Select parent </option>
</select>
Run Code Online (Sandbox Code Playgroud)

编辑: 根据评论

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

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

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

public class CreateProject
{
  public string parent { set;get;}
  public string ProjectName { set;get;}
}
Run Code Online (Sandbox Code Playgroud)

并在您的操作方法中。

[HttpPost]
public ActionResult Create(CreateProject model)
{

  // check model.parent value.
}
Run Code Online (Sandbox Code Playgroud)