[英]DropDownList C# Mvc4 Razor
I don't understand how to pass this selectListitem in the controller, how to send that to the view ? 我不明白如何在控制器中传递此selectListitem,如何将其发送到视图? With
return view("MyView", listItems )
? 与
return view("MyView", listItems )
? But it says that listItems
doesn't exist in the current context ! 但是它说
listItems
在当前上下文中不存在! Have you an idea ? 你有主意吗? Thanks
谢谢
@{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Exemplo1",
Value = "Exemplo1"
});
listItems.Add(new SelectListItem
{
Text = "Exemplo2",
Value = "Exemplo2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Exemplo3",
Value = "Exemplo3"
});
}
@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")
I precise that there is already a model in my view for a form. 我认为我认为表单已经有一个模型。 I want to fill one field of the form with the dropdownlist.
我想用下拉列表填充表单的一个字段。 That's why i whant to use the HtmlHelper
DropDownListFor
. 这就是为什么我想要使用HtmlHelper
DropDownListFor
。
You're going to want to define a model, and pass that model class into the view. 您将要定义一个模型,并将该模型类传递到视图中。 Ditch ViewBag and use a strongly typed model.
抛开ViewBag并使用强类型模型。
public class ViewModel
{
public int ddlSelectedValue {get; set;}
List<System.Web.Mvc.SelectListItem> DDLItems { get; set; } //Instantiate this through Constructor
}
ViewModel model = new ViewModel();
int val = 5;
model.DDLItems.Add( new SelectListItem() { Text = "Text", Value = Val.ToString() });
return view (model)
View
@model NameSpace.ViewModel
@Html.DropDownListFor(x => x.ddlSelectedValue, Model.DDLItems)
HERE GO IN THE VIEW @{ 进入视野@ {
List<User> listaUsers = (List<User>)ViewBag.ListUser;
} }
foreach (User us in listaUsers)
{
<option value="@us.UserID">@us.Name</option>
}
</select>
/// Name function its like name of view for binding this part go to the controller
public ActionResult anytingName()
{
User us= new User();
us.Name="paul";
us.UserID=1;
List<User> users= new List<User>();
users.Add(us);
ViewBag.ListUser = users;
return View();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.