user1258261
user1258261

Reputation: 11

DropDownList asp.net mvc 3 problems

i Show a data in the DropDownList:(im usign datacontext)

Controller:

var query = newdb.Incident.Select(c => new { c.ID, c.Name }); ViewBag.items = new SelectList(query.AsEnumerable(), "ID", "Name");

View:

@Html.DropDownList("items", (SelectList) ViewBag.items, "--Select a Incident--")

Problem:

i want to know how i can select a item from the DropDownlist and send a parameter back to the controller of the item selected, because i try this and dont work:

@using (Html.BeginForm("er", "er", FormMethod.Post, new { id = 4 })){

@Html.DropDownList("items", (SelectList) ViewBag.items, "--Select a Incident--")}

i hope somebody can helpLaughing

Upvotes: 0

Views: 530

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You could pass the selected value as 4th argument of the SelectList constructor:

var query = newdb.Incident.Select(c => new { c.ID, c.Name }); 
ViewBag.items = new SelectList(query.AsEnumerable(), "ID", "Name", "4");

and also in your view make sure that you are using a different value as first argument to the DropDownList helper because right now you are using "items" which is wrong, because the first argument represents the name of the generated dropdownlist that will be used back in the controller to fetch the selected value:

@Html.DropDownList(
    "selectedIncidentId", 
    (SelectList) ViewBag.items, 
    "--Select a Incident--"
)

Also I would recommend you using view models and the strongly typed version of the DropDownListFor helper:

public class IncidentsViewModel
{
    public int? SelectedIncidentId { get; set; }
    public IEnumerable<SelectListItem> Incidents { get; set; }
}

and then:

public ActionResult Foo()
{
    var incidents = newdb.Incident.ToList().Select(c => new SelectListItem
    { 
        Value = c.ID.ToString(), 
        Text = c.Name 
    }); 
    var model = new IncidentsViewModel
    {
        SelectedIncidentId = 4, // preselect an incident with id = 4
        Incidents = incidents
    }
    return View(model);
}

and in your strongly typed view:

@model IncidentsViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.SelectedIncidentId, 
        Model.Incidents, 
        "--Select a Incident--"
    )

    <button type="submit">OK</button>
}

Upvotes: 1

Related Questions