如何绑定下拉列表以使用viewdata [英] How to bind dropdown list for using viewdata
问题描述
我在我看来写了以下代码。
I have written following code in my view.
<pre lang="c#">
<%Html.DropDownListFor("ddlCity",new SelectList(ViewData["City"].ToString(),"Value","Text"));%>
以及控制器中的以下代码
and following code in the controller
<pre lang="c#">
public ActionResult Index()
{
DbConnect objdb = new DbConnect();
DataTable dt= objdb.ExecuteDataset("usp_allCities");
List<SelectListItem> cityList=new List<SelectListItem>();
for (int i = 0; i < dt.Rows.Count; i++)
{
cityList.Add(new SelectListItem { Text = dt.Rows[i]["CityName"].ToString(), Value = dt.Rows[i]["CityId"].ToString() });
}
ViewData["City"] = (IEnumerable<SelectListItem>)cityList;
return View(ViewData);
}
我无法绑定下拉列表。任何人都可以建议我该怎么做?
浏览器给出以下错误 -
CS0411:方法'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<的类型参数; tmodel,tproperty>(System.Web.Mvc.HtmlHelper< tmodel>,System.Linq.Expressions.Expression< system.func>< tmodel,tproperty>>,System.Collections.Generic.IEnumerable< system.web。 mvc.selectlistitem>)'无法从使用中推断出来。尝试明确指定类型参数。
I am not able to bind the dropdown list. Can any one suggest me what can i do?
Browser gives following error -
CS0411: The type arguments for method 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<tmodel,tproperty>(System.Web.Mvc.HtmlHelper<tmodel>, System.Linq.Expressions.Expression<system.func><tmodel,tproperty>>, System.Collections.Generic.IEnumerable<system.web.mvc.selectlistitem>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
推荐答案
尝试使用@ Html.DropDownList而不是DropDownListfor
您不能使用Helper @ Html.DropdownListFor,因为第一个参数不正确将您的助手更改为:
Try using @Html.DropDownList instead DropDownListfor
You cannot used that Helper @Html.DropdownListFor, because the first parameters was not correct change your helper to:
@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
@ Html.DropDownListFor在第一个参数中接收一个lambda所有重载中的表达式用于创建强类型下拉菜单
如果您对某些模型强烈键入View,则可以使用帮助程序更改代码以创建强类型下拉列表,类似
@Html.DropDownListFor receive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns
If your View it's strongly typed to some Model you may change your code using a helper to created a strongly typed dropdownlist, something like
@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
这是文档
; _)
Here is Documentation
;_)
以正常方式设置ViewData,分配一个映射到模型中将绑定在Post上的属性的键名。
Set up your ViewData in the normal way, assigning a Key name that maps to a property in your model that will be bound on Post .
ViewData["ModelPropertyName"] = new SelectList(...)
然后在你的视图中添加一个Html.DropDownList ...
Then in your view simply add a Html.DropDownList ...
@Html.DropDownList("ModelPropertyName")
快乐编码; - )
Happy coding ;-)
试试这个..
try this..
@Html.DropDownList("Select", new SelectList((System.Collections.IEnumerable)ViewData["list"], "Id", "Name"))
这篇关于如何绑定下拉列表以使用viewdata的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!