IT story

MVC3 DropDownListFor-간단한 예?

hot-time 2020. 8. 2. 17:19
반응형

MVC3 DropDownListFor-간단한 예?


DropDownListForMVC3 앱에 문제가 있습니다. StackOverflow를 사용하여 View에 표시하는 방법을 알아낼 수 있었지만 이제는 제출 될 때 View Model에서 해당 특성의 값을 캡처하는 방법을 모르겠습니다. 이 작업을 수행하려면 ID 및 값 속성이있는 내부 클래스를 만들어야 IEnumerable<Contrib>했고 DropDownListFor매개 변수 요구 사항 을 충족시키기 위해 를 사용해야했습니다 . 그러나 이제 MVC FW는이 드롭 다운에서 선택한 값을 뷰 모델의 간단한 문자열 속성으로 다시 매핑해야합니까?

public class MyViewModelClass
{
    public class Contrib
    {
        public int ContribId { get; set; }
        public string Value { get; set; }
    }

    public IEnumerable<Contrib> ContribTypeOptions = 
        new List<Contrib>
        {
            new Contrib {ContribId = 0, Value = "Payroll Deduction"},
            new Contrib {ContribId = 1, Value = "Bill Me"}
        };

    [DisplayName("Contribution Type")]
    public string ContribType { get; set; }
}

내보기에서 다음과 같이 페이지에 드롭 다운을 놓습니다.

<div class="editor-label">
    @Html.LabelFor(m => m.ContribType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId, 
             new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))
</div>

양식을 제출하면 ContribTypeis (물론) null입니다.

이를 수행하는 올바른 방법은 무엇입니까?


당신은 이렇게해야합니다 :

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

어디:

m => m.ContribType

결과 값이있는 속성입니다.


나는 이것이 도움이 될 것이라고 생각한다 : Controller에서 목록 항목과 선택된 값을 얻는다.

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

그리고보기

@Html.DropDownList("CategoryId",String.Empty)

DropDownList에서 동적 데이터를 바인딩하기 위해 다음을 수행 할 수 있습니다.

아래와 같이 컨트롤러에서 ViewBag 생성

ViewBag.ContribTypeOptions = yourFunctionValue();

이제이 값을 아래와 같이 사용하십시오.

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")

     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

여기서 Value는 선택한 값을 저장하려는 모델의 객체입니다.

참고 URL : https://stackoverflow.com/questions/7142961/mvc3-dropdownlistfor-a-simple-example

반응형