2

i have problem in dropdownlist selected value.

View

@Html.DropDownList("QuestionType", (IEnumerable<SelectListItem>)ViewData["questiontype"], new { id = "QuestionType", @style = "max-width: 200px;width: 200px", @OnChange = "HideForm(this)", @class = "form-control" })

Controller

var questionTypeList = new SelectList(
                    new List<SelectListItem> 
                    { 
                        new SelectListItem { Value = "1", Text = "Automatic", Selected = false },
                        new SelectListItem { Value = "2", Text = "Custom", Selected = true}
                    }, "Value", "Text"
                ).ToList();
var questionType = new SelectList(questionTypeList, "Value", "Text");
ViewData["questiontype"] = questionType;

i want value=2 is selected true in view but my script above is not working, how can i solve this problem?

i have modified my code. i'm not using stronglytype which bind to dropdownlist. i'm using viewdata. this is my code:

Controller

List<SelectListItem> questionTypeList = new List<SelectListItem>();
            questionTypeList.Add(new SelectListItem() { Text = "Automatic", Value = "1" });
            questionTypeList.Add(new SelectListItem() { Selected = true, Text = "Custom", Value = "2" });
ViewData["questiontype"] = questionTypeList;

View

@Html.DropDownList("QuestionType", ViewData["questiontype"] as SelectList,  new { id = "QuestionType", @style = "max-width: 200px;width: 200px", @OnChange = "HideForm(this)", @class = "form-control" })

why this code work and why previous code not work? i'm so confuse...

4

1 回答 1

1

不确定您是否有强类型视图,但可以使用

    DropdownlistFor(model=>model.QuestionType, selectlistItem)

然后在你的控制器集中

model.QuestionType to 2;

然后

return View(model);
于 2014-06-18T03:04:19.927 回答