所选值的Html.Dropdownlist无效

时间:2014-08-12 19:32:40

标签: c# asp.net-mvc razor

我无法使用HTML.dropwdownlistfor

获取所选值

这是我试图开始工作,所有数据都在那里,select语句找到所选项目,SelectListItems的ienumerable有一个项目具有“select = true”我不知道我在哪里我错了。

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

帮助方法:

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

控制器:(投射工作正常,数据存在)

[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)

感谢您提供任何见解/帮助!!!

1 个答案:

答案 0 :(得分:1)

如果您要使用DropDownListFor,则需要先在模型中设置所选值。

在您的操作(或模型构建器)中:

model.Location_Model = "my selected value";

然后你的观点:

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