Reputation: 915
My apologies I will not try technical terms to explain my problem, I will try basic English - I want to have my select list to appear in my view with he current selected dealer chosen already (more details below). Thank you in Advance.
I have a product which is stored in its own data table, which is sold by dealers and against the product I store the dealer number who sold it.
I get the dealer number from the dealer data table.
On the web page I create a drop down list when the product is sold which the user selects the dealer name who sold it. I have managed to create the list which shows the names but when selected stores the ID in the product table of the dealer this is working fine.
I am just struggling when I come to edit the product have the select list appear and show the current selected dealer, it always appears with first dealer in the list. I have searched but due to my getting this code fudged together from other SO posts, I can not find a post which works with my code example.
Any feedback/help/suggestions would be greatly appreciated.
Controller
// Create drop down list of dealer names to allow users to select from easily identifiable list rather than find number first before coming to the page.
var list = db.Dealers.OrderBy(r => r.Name).ToList().Select(rr =>
new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); // Require to code and set value based on current selected name.
ViewBag.DealerName = list;
Razor view Code:
<div class="form-group">
@Html.LabelFor(model => model.Dealer_ID, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@*
@* Custom display for drop down list which shows Dealer Name instead of numeric ID Value *@
@Html.DropDownListFor(m => m.Dealer_ID, (IEnumerable<SelectListItem>)ViewBag.DealerName, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
Upvotes: 1
Views: 3405
Reputation: 3744
You store model.Name
to the Value
of SelectListItem
, but it should be property that correspond to the value of model.Dealer_ID
rr.ID
or rr.Dealer_ID
:
var list = db.Dealers.OrderBy(r => r.Name).ToList().Select(rr =>
new SelectListItem { Value = rr.Dealer_ID.ToString(), Text = rr.Name }).ToList();
Upvotes: 3