Reputation: 716
I don't understand how to pass this selectListitem in the controller, how to send that to the view ?
With return view("MyView", listItems )
? But it says that listItems
doesn't exist in the current context ! 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
.
Upvotes: 0
Views: 181
Reputation: 86
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();
}
Upvotes: 0
Reputation: 5590
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.
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)
Upvotes: 1