oorosco
oorosco

Reputation: 246

Html.Dropdownlistfor selected value is not working

I can't get the selected value to work with HTML.dropwdownlistfor

Here is what I have trying to get to work, ALL DATA IS THERE, the select statement finds the selected item, the ienumerable of SelectListItems has an item that has the "select = true" I'm not sure where I'm going wrong.

MODEL:

[SitecoreIgnore]
public virtual IEnumerable<Sitecore.Data.Items.Item> List_Location { get; set; }
public virtual Sitecore.Data.Items.Item Location { get; set; }
[SitecoreIgnore]
public virtual string Location_Model { get; set; }

HELPER METHOD:

public static IEnumerable<SelectListItem> SelectListConstructor(Item selectedItem, IEnumerable<Item> options)
{
IEnumerable<SelectListItem> listings = from o in options
select new SelectListItem
{
Selected = (selectedItem.ID == o.ID),
Text = o.DisplayName,
Value = o.ID.ToString()
};



return listings;            
}

Controller: (The casting works fine, data is there)

[HttpPost]
public ActionResult CreateAdStep(Classified model)
{
if(ModelState.IsValid)
{
return RedirectToAction("PreviewAd", model);
}

var allerrrors = ModelState.Values.SelectMany(v => v.Errors);

return View(Sitecore.Context.Database.GetItem("{69040A7B-5444-4ECF-A081-C4A3B26876B5}").GlassCast<Classified>());
}

[HttpGet]
public ActionResult CreateAdStep()
{
var trial = Sitecore.Context.Database.GetItem("{69040A7B-5444-4ECF-A081-C4A3B26876B5}").GlassCast<Classified>();
return View(trial);
}

CSHTML LINE ATTEMPTS: 1)

@{ var emo = CalCPA.Source.Models.Utility.Utility.SelectListConstructor(Model.Location, Model.List_Location);
var emo2 = emo.Where(i=> i.Selected == true).FirstOrDefault();
}
@Html.DropDownListFor(m => m.Location_Model, new SelectList(emo, "Value", "Text", emo2.Value))

2)

@{ var emo = CalCPA.Source.Models.Utility.Utility.SelectListConstructor(Model.Location, Model.List_Location);
var emo2 = emo.Where(i=> i.Selected == true).FirstOrDefault();
}
@Html.DropDownListFor(m => m.Location_Model, new SelectList(emo, "Value", "Text", emo2))

3)

@{ var emo = CalCPA.Source.Models.Utility.Utility.SelectListConstructor(Model.Location, Model.List_Location);
var emo2 = emo.Where(i=> i.Selected == true).FirstOrDefault();
}
@Html.DropDownListFor(m => m.Location_Model, emo)

Thanks for any insight/help!!!

Upvotes: 1

Views: 5219

Answers (1)

mxmissile
mxmissile

Reputation: 11681

If your going to use DropDownListFor you need to set the selected value in the model first.

In your action (or model builder):

model.Location_Model = "my selected value";

Then your view:

@Html.DropDownListFor(m => m.Location_Model, new SelectList(emo, "Value", "Text"))

Upvotes: 4

Related Questions