Vikram Singh Saini
Vikram Singh Saini

Reputation: 1889

How to get dynamic dropdownlist selected value

I am new to MVC and using MVC4 for project.

Here is the piece of code in view -

@model SomeModel

@{
for (var i = 0; i < Model.NumberOfQuestions; i++)
{

<div class="ques">
    <div class="leftCol">
        <label>@Resources.Enroll.Question</label>
    </div>
    <div class="rightCol">
        @Html.DropDownListFor(m => m.Question, Model.Questions, new { id = "ddlQuestion" + i, @data_native_menu = "false", onchange = "SelectedIndexChanged(id)" })

        @Html.ValidationMessageFor(m => m.Question)
    </div>

    <div class="clear" />
    <div id="@("customQuestion" + i)" class="hide">
        <div class="leftCol">
            <label>@Resources.Enroll.CustomQuestion</label>
        </div>
        <div class="rightCol">
            @Html.TextBoxFor(m => m.CustomQuestion, new { id = "txtCustomQues" + i })
            @Html.ValidationMessageFor(m => m.CustomQuestion)
        </div>
    </div>
    <div class="clear" />
    <div class="leftCol">
        <label>@Resources.Enroll.Answer</label>
    </div>
    <div class="rightCol">
        @Html.TextBoxFor(m => m.Answer, new { id = "txtAnswer" + i })
        @Html.ValidationMessageFor(m => m.Answer)
    </div>

    <div class="clear" />
</div>  
}
}

The problem here is I'm not able to get some way of managing selected value for all dropdownlist and passing them to controller.

I am able to get single value retained in Question which is a public property in Model. But I am not getting how to do for all dynamically.

Can you please guide me how to do same?

Upvotes: 2

Views: 1492

Answers (1)

hutchonoid
hutchonoid

Reputation: 33306

Create a view model that represents the questions you are going to select i.e.

public class QuestionViewModel
{
    public string QuestionId { get; set; }
}

Then add them to your existing model, without seeing your current one it should resemble this:

public class QuestionsViewModel
        {
            public QuestionsViewModel()
            {
                SelectedQuestions = new List<QuestionViewModel>();
            }
            public List<SelectListItem> QuestionsSelectList { get; set; }
            public List<QuestionViewModel> SelectedQuestions { get; set; }
        }

Use indexing in your for loop with the count of the Questions. The important bit is how the QuestionId is used by the model binder to send it back in the post:

@for(var i = 0; i < Model.SelectedQuestions.Count; i++)
{
    @Html.DropDownListFor(m => m.SelectedQuestions[i].QuestionId, Model.QuestionsSelectList as List<SelectListItem>, "Select..", new { @data_native_menu = "false", onchange = "SelectedIndexChanged(id)" })
}

When the form is submitted you will have a collection of selected questions i.e.

var selectedQuestion1 = model.SelectedQuestions[0].QuestionId;

Selected Questions

Upvotes: 1

Related Questions