Bojangles
Bojangles

Reputation: 467

Drop Down Box not returning the Value

I have the following code populating a dropdown box, it selects the current RunArea assigns it to the selected Run with run.RunRunAreaID but when I update the Run, the RunArea Drop Down it's not sending the ID back, so I end up with NULL

My Controller

public ActionResult Edit(int? id)
{
    Run run = db.Runs.Find(id);

    ViewBag.RunAreaName = new SelectList(db.RunAreas, "ID", "RunAreaName", run.RunRunAreaID);

    return View(run);
}

My View

@Html.DropDownList("RunAreaName")

This is all done in the Run controller, the Drop Down is populated with Run Areas form a different table/Model, so One Run Area has Many Runs.

Edit

I have five Run Areas and they are all being passed through to the view, all five Run Areas display in the drop down box with the correct one selected for that particular Run, hence why I need run.RunRunAreaId. That all works fine.

But if I update/change the Run Area in the Drop Down, the view returns NULL for that field.

Edit

RunArea Model

public partial class RunArea
{
    public int ID { get; set; }
    public string RunAreaName { get; set; }

    public List<Run> Runs { get; set; }
}

Run Model

public partial class Run
{
    public int ID { get; set; }
    public int RunReportID { get; set; }
    public int RunRunAreaID { get; set; }
    public string RunName { get; set; }
    public bool RunSnowmaking { get; set; }
    public bool RunGroomed { get; set; }
    public bool RunDisplaySnowmaking { get; set; }
    public bool RunLikely { get; set; }

    public RunArea RunArea { get; set; }
}

Lazy loading is turned off as they are pushing out XML

Upvotes: 0

Views: 58

Answers (2)

Doan Cuong
Doan Cuong

Reputation: 2614

I hope this will work for you

ViewBag.RunAreaName = new SelectList(db.RunAreas, "ID", "RunAreaName", run.RunRunAreaID);

In your View:

using (@Html.BeginForm(//add your form setting))
{
    //first parameter to set id and name for drop down list
    //second parameter bind data to it.
    @Html.DropDownList("RunRunID", (SelectList)ViewBag.RunAreaName)
    //add some other property here
}

Notice that I changed ID to RunRunAreaID in ViewBag.RunAreaName. This will bind your dropdownlist value to Model.RunRunAreaID when submit to server

Upvotes: 1

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

use this in your view

@Html.DropDownList("RunAreaName",ViewBag.RunAreaName as SelectList,"Select Text")

Also in here

ViewBag.RunAreaName = new SelectList(db.RunAreas, "ID", "RunAreaName", run.RunRunAreaID);

I don't think you need run.RunRunAreaId

ViewBag.RunAreaName = new SelectList(db.RunAreas, "ID", "RunAreaName") 

is enough

Upvotes: 0

Related Questions