Program Club

DropDownListFor Not 선택 값

proclub 2020. 10. 17. 12:34
반응형

DropDownListFor Not 선택 값


편집 페이지 내에서 DropDownListFor 도우미 메서드를 사용하고 있으며 지정한 값을 선택하는 데 운이 없습니다. Stackoverflow 에서 비슷한 질문발견했습니다 . 제안 된 해결 방법은 "보기 코드에서 SelectList 채우기"였습니다. 문제는 이미 이것을 시도했지만 여전히 작동하지 않는다는 것입니다.

<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>

중단 점을 설정하고 model.AddressStateAbbr의 존재 (및 유효성)를 확인했습니다. 내가 무엇을 놓치고 있는지 잘 모르겠습니다.


한 시간 동안 조사한 결과 선택한 항목이로 설정되지 않는 문제를 발견했습니다 DropDownListFor. 그 이유는 모델의 속성과 동일한 ViewBag의 이름을 사용하고 있기 때문입니다.

public  class employee_insignia
{ 
   public int id{get;set;}
   public string name{get;set;}
   public int insignia{get;set;}//This property will store insignia id
}

// If your ViewBag's name same as your property name 
  ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

전망

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")

선택한 옵션은 드롭 다운 목록으로 설정되지 않지만 ViewBag의 이름을 다른 이름으로 변경하면 선택한 옵션이 올바르게 표시됩니다.

ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

전망

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")

시험:

<%= Html.DropDownListFor(
    model => model.AddressStateAbbr,
    new SelectList(
        Model.States.OrderBy(s => s.StateAbbr),
        "StateAbbr",
        "StateName",
        Model.AddressStateAbbr), "-- Select State --")%>

또는 Razor 구문 :

@Html.DropDownListFor(
    model => model.AddressStateAbbr,
    new SelectList(
        Model.States.OrderBy(s => s.StateAbbr),
        "StateAbbr",
        "StateName",
        Model.AddressStateAbbr), "-- Select State --")

식 기반 도우미는 SelectList에서 SelectListItems의 Selected 속성을 존중하지 않는 것 같습니다.


이 모든 ViewBag 이상한 점과는 달리 올바르게 수행하고 모델을 사용하고 있으며 여전히 문제가 발생하면 .NET 의 선택 사항 @Html.DropDownListFor(m => m.MyValue, @Model.MyOptions)과 일치 할 수 없기 때문 MyValue입니다 MyOptions. 이에 대한 두 가지 잠재적 인 이유는 다음과 같습니다.

  1. MyValuenull입니다. ViewModel에서 설정하지 않았습니다. 하나 만들기 MyOptionsSelected=true이 문제를 해결하지 것이다.
  2. 더 미묘하게도의 유형유형MyValue다릅니다 MyOptions. 그래서 만약 MyValueis (int) 1이지만 MyOptions패딩 된 문자열 목록 {"01", "02", "03", ...}이라면 분명히 아무것도 선택하지 않을 것입니다.

이 질문을 다루지는 않지만 미래의 Google 사용자가 내 생각 경로를 따를 경우 도움이 될 수 있습니다.

다중 선택을 원했고 DropDownListFor 의이 속성 해킹이 자동 선택되지 않았습니다.

Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })

대신 모든 것이 작동하도록 만든 ListBoxFor사용해야 했습니다.

Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)

나는 또한 비슷한 문제가 있으며 다음과 같이 해결하고

컨트롤러의 model.States 속성을 선택해야하는 항목으로

model.States = "캘리포니아"

그러면 기본값으로 "California"가 표시됩니다.


this problem is common. change viewbag property name to other then model variable name used on page.


One other thing to check if it's not all your own code, is to make sure there's not a javascript function changing the value on page load. After hours of banging my head against a wall reading through all these solutions, I discovered this is what was happening with me.


I encountered this issue recently. It drove me mad for about an hour. In my case, I wasn't using a ViewBag variable with the same name as the model property.

After tracing source control changes, the issue turned out to be that my action had an argument with the same name as the model property:

public ActionResult SomeAction(string someName)
{
    var model = new SomeModel();
    model.SomeNames = GetSomeList();
    //Notice how the model property name matches the action name
    model.someName = someName; 
}

In the view:

@Html.DropDownListFor(model => model.someName, Model.SomeNames)

I simply changed the action's argument to some other name and it started working again:

public ActionResult SomeAction(string someOtherName)
{
    //....
}

I suppose one could also change the model's property name but in my case, the argument name is meaningless so...

Hopefully this answer saves someone else the trouble.


The issue at least for me was tied to the IEnumerable<T>.

Basically what happened was that the view and the model did not have the same reference for the same property.

If you do this

IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}

Then bind this using the

@Html.DropDownListFor(model => model.Id, Model.CoolNames)

The View loses track of the CoolNames property, a simple fix is just to add .ToList() After dooing a projection (.Select()) ;).


I had the same problem. In the example below The variable ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] has a SelectListItem list with a default selected value but such attribute is not reflected visually.

// data 
        var p_estadoAcreditacion = "NO";
        var estadoAcreditacion = new List<SelectListItem>();
        estadoAcreditacion.Add(new SelectListItem { Text = "(SELECCIONE)"    , Value = " "    });
        estadoAcreditacion.Add(new SelectListItem { Text = "SI"              , Value = "SI"   });
        estadoAcreditacion.Add(new SelectListItem { Text = "NO"              , Value = "NO"   });

        if (!string.IsNullOrEmpty(p_estadoAcreditacion))
        {
            estadoAcreditacion.First(x => x.Value == p_estadoAcreditacion.Trim()).Selected = true;
        }
         ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] = estadoAcreditacion;

I solved it by making the first argument of DropdownList, different to the id attribute.

// error:
@Html.DropDownList("SELECT__ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id         = "SELECT__ACREDITO_MODELO_INTEGRADO"
...
// solved :
@Html.DropDownList("DROPDOWNLIST_ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id         = "SELECT__ACREDITO_MODELO_INTEGRADO"

...

참고URL : https://stackoverflow.com/questions/2278056/dropdownlistfor-not-selecting-value

반응형