简体   繁体   中英

DropDownList C# Mvc4 Razor

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 .

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)

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM