2013-03-26 126 views
2

我想创建一个空的下拉列表中刚刚默认value.I使用下面的代码:如何用默认值创建一个空的下拉列表?

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

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

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

我该如何解决呢? 谢谢。

+0

试试这个'@ Html.DropDownList(null,“--Select Parent - ”)''。 – 2013-03-26 15:04:10

+0

@MichaelPerrenoud:现在错误更改为:值不能为空或为空。 参数名称:名称 – 2013-03-26 15:11:00

+0

好的,那就行不通了。你需要按照@Shyju的方向。问题是它试图绑定到名为“parent”的属性。 – 2013-03-26 15:12:42

回答

4

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

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

编辑:按注释

当您提交表单,您可以通过其参数与parent名获得所选值

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

OR在你的视图模型一个parent属性,它使用的是型号结合。

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

和您的操作方法。

[HttpPost] 
public ActionResult Create(CreateProject model) 
{ 

    // check model.parent value. 
} 
+0

但是这种HTML对象不会以这样的形式排列: @using(Html.BeginForm()) {} – 2013-03-26 15:10:04

+0

当然会。无论使用何种Helper方法(例如:Html.DropDownListFor),也只会生成这样的HTML标记。在你的'HttpPost'动作中,你可以在你的视图模型中使用'parent'参数或者拥有'parent'属性。 – Shyju 2013-03-26 15:12:01

+0

明白了。)。) – 2013-03-26 15:14:46

0

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

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

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

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

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

+0

谢谢你的部分帮助我返回空的下拉列表。我的代码: IW.SelItemList = new SelectList(Enumerable.Empty ()); – 2016-01-07 07:15:27

2

将html属性添加到上述示例中:

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

**从审核队列**:我可以请求您在源代码中添加一些上下文。仅有代码的答案很难理解。如果您可以在帖子中添加更多信息,它可以帮助提问者和未来的读者。 – RBT 2017-05-23 07:58:58