最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net mvc - Clearing the Selected Value in @Html.DropDownListFor - Stack Overflow

programmeradmin3浏览0评论

I have a DropdownListFor:

@Html.DropDownListFor(m => m.SelectedOccupation, (IEnumerable<SelectListItem>)ViewBag.Occupations, new { placeholder = "Select Occupation", onchange = "form.submit();", style = "width:170px" }) &emsp;

This is populated from the following code:

public IList<SelectListItem> GetOccupations(string CurrentOccupation)
{
    var Occupations=_MapsContext.OccupationDesignations.OrderBy(e=>e.Occupation).ToList();
    List<SelectListItem>OccupationList=new List<SelectListItem>();
    OccupationList.Add(new SelectListItem
    {
        Value = "Select Occupation/Designation",
        Text = "Select Occupation/Designation",
        Selected = true
     });
    foreach(var item in Occupations)
    {
       OccupationList.Add(new SelectListItem
       {
           Value = item.Occupation,
           Text = item.Occupation,
           Selected = item.Occupation == CurrentOccupation
        });
}
return OccupationList;

The controller calls this with:

ViewBag.Occupations = _mapRepository.GetOccupations("");

This works fine when the page opens showing the message "Select Occupation/Designation", an occupation is selected and the data on the page filtered accordingly. If a different occupation is selected that all works fine. However, there is a 'clear' button on the form which resets this and other filters. I want this to return to dropdownlist to show the original message "Select Occupation/Designation", I've tried clear the m.SelectedOccupation which resides in a virtual model - vm.SelectedOccupation="". I've checked the above code that populates the list and it shows the first item (item 0) as 'Selected', but the DropDownListFor goes on showing the previous selection.

发布评论

评论列表(0)

  1. 暂无评论