두 번째 드롭 다운의 첫 번째 인수와 같은 이름을 사용해서는 안됩니다. 귀하의 예에서는 선택한 값과 사용 가능한 값 목록을 저장하는 데 productType
을 사용했습니다.
<%= Html.DropDownList(
"selectedProductType",
ViewData["productType"] as SelectList,
"defaultValue"
) %>
와 컨트롤러 액션 내부
당신이 그 중 2 곳이 설정할 수 있습니다 :
ViewData["selectedProductType"] = "abc";
ViewData["productType"] = new SelectList(myDropDownList);
이 이미 요소가 있다고 가정 ASP.NET MVC에서 드롭 다운을 렌더링하기 위해 당신은 2 곳이 필요 제품 유형의 드롭 다운 목록에 value="abc"
을 입력하십시오. 그러면 값이 자동으로 미리 선택됩니다.
드롭 다운 목록을 렌더링하는 대신 다른 방법을 추천합니다.
public class ProductViewModel
{
public string SelectedProductType { get; set; }
public IEnumerable<SelectListItem> ProductTypes { get; set; }
}
가 당신이보기 모델을 채 웁니다 컨트롤러 액션을 가지고 뷰에 전달합니다 : 그것은보기 데이터의 제거 점점보기 모델을 도입하고, 도우미의 강력한 형식의 버전을 사용하여 구성
당신의 강력한 형식의 내부보기
public ActionResult SomeAction()
{
var model = new ProductViewModel();
// preselected an element with value = "type2"
model.SelectedProductType = "type2";
// bind the available product types
model.ProductTypes = new SelectList(
// Obviously those could come from a database or something
new[] {
new { Value = "type1", Text = "product type 1" },
new { Value = "type2", Text = "product type 2" },
new { Value = "type3", Text = "product type 3" },
new { Value = "type4", Text = "product type 4" },
},
"Value",
"Text"
);
// pass the view model to the view
return View(model);
}
마지막 : 나는 사람이 모두 같은 이름을 사용하는 모든 게시물에 대한 니켈이 있다면
<%= Html.DropDownListFor(
x => x.SelectedProductType,
Model.ProductTypes,
"defaultValue"
) %>
맹세, 난 아주 부자가 될 것입니다. 나는 이것이 왜 그렇게 흔한 것인지 전혀 모른다. 이 같은 문제가 하루에 여러 번 나타나는 것 같습니다. –
대단히 감사합니다! – Athena