我想創建一個空的下拉列表中剛剛默認value.I使用下面的代碼:如何用默認值創建一個空的下拉列表?
@Html.DropDownList("parent","--Select Parent--")
但在運行時我看到這個錯誤:
There is no ViewData item of type 'IEnumerable' that has the key 'parent'.
我該如何解決呢? 謝謝。
我想創建一個空的下拉列表中剛剛默認value.I使用下面的代碼:如何用默認值創建一個空的下拉列表?
@Html.DropDownList("parent","--Select Parent--")
但在運行時我看到這個錯誤:
There is no ViewData item of type 'IEnumerable' that has the key 'parent'.
我該如何解決呢? 謝謝。
您可以在視圖中簡單地創建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.
}
但是這種HTML對象不會以這樣的形式排列: @using(Html.BeginForm()) {} – 2013-03-26 15:10:04
當然會。無論使用何種Helper方法(例如:Html.DropDownListFor),也只會生成這樣的HTML標記。在你的'HttpPost'動作中,你可以在你的視圖模型中使用'parent'參數或者擁有'parent'屬性。 – Shyju 2013-03-26 15:12:01
明白了。)。) – 2013-03-26 15:14:46
你可以做這樣的事情在你的控制器建立一個空的下拉列表
ViewBag.ClassID = new SelectList(db.Classes.Where(c => c.ClassID == 0) , "ClassID", "ClassName").ToList();
你可以建一個空的DropDownList像這樣:
@Html.DropDownList("parent", Enumerable.Empty<SelectListItem>(), "--Select Parent--")
參考:Build an empty MVC DropdownListFor for a Cascade Sub-List
謝謝你的部分幫助我返回空的下拉列表。我的代碼: IW.SelItemList = new SelectList(Enumerable.Empty
將html屬性添加到上述示例中:
@Html.DropDownList("Idparent", Enumerable.Empty<SelectListItem>(), "Select one...", new {@class="form-control"})
**從審覈隊列**:我可以請求您在源代碼中添加一些上下文。僅有代碼的答案很難理解。如果您可以在帖子中添加更多信息,它可以幫助提問者和未來的讀者。 – RBT 2017-05-23 07:58:58
試試這個'@ Html.DropDownList(null,「--Select Parent - 」)''。 – 2013-03-26 15:04:10
@MichaelPerrenoud:現在錯誤更改爲:值不能爲空或爲空。 參數名稱:名稱 – 2013-03-26 15:11:00
好的,那就行不通了。你需要按照@Shyju的方向。問題是它試圖綁定到名爲「parent」的屬性。 – 2013-03-26 15:12:42