简体   繁体   中英

Get selected radiobutton values in MVC

I have below Model structure

public class Quiz
{
    public List<Question> Questions { get; set; }
}

public class Question
{
    public int Id { get; set; }
    public String QuestionText { get; set; }
    public List<Option> Options { get; set; }
    public int AnswerId { get; set; }
}

public class Option
{
    public int Id { get; set; }
    public String OptionText { get; set; }
    public int DisplayOrder { get; set; }
}

And my view is like below where I am displaying all the questions and options

foreach (var question in Model.Questions)
{
    @Html.DisplayFor(modelItem => question.QuestionText) <br />
    foreach (var option in question.Options)
    {
        @Html.RadioButton("Id", option.Id)@option.OptionText
    }
}
<input type="submit" value="Submit" />

I am not getting the values for all selected radiobuttons, It always returns one value in form collection

[HttpPost]
public ActionResult Quiz(Quiz userResponse, FormCollection form)
{
    foreach (var item in form.AllKeys)
    {
        string value = form[item];
        // save data 
    }
    //var selectedOption = frm["Id"];
    return View();
}

Can you please help?

You creating radio buttons that have no relationship to you model and all have the same name="Id" attribute (and you would only ever be able to select one option from all the questions). You need to use a for loop or EditorTemplate for typeof Question (refer this answer for a more detailed explanation). Using an EditorTemplate , your code will be

/Views/Shared/EditorTemplates/Question.cshtml

@model Question
@Html.HiddenFor(m => m.Id)
@Html.DisplayFor(m => m.QuestionText)
@foreach(var option in Model.Options)
{
    <div>
        <label>
            @Html.RadioButtonFor(m => m.AnswerId , option,Id, new { id = "" })
            <span>@option.OptionText</span>
        </label>
    </div>
}

and in the main view

@model Quiz
@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.Questions)
    <input type="submit" value="Save" />
}

and the controller method

[HttpPost]
public ActionResult Quiz(Quiz model)

The model in the POST method will be bound with each question containing its Id and AnswerId (the Id of the selected Option ) properties.

Side note: Your current POST method has return View() but this would fail because the value of each Options property will be null . If you need to return the view (which should only be necessary if ModelState is invalid), then you need to repopulate those collections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM