c# - Asp.net MVC Razor how to show grouped radio buttons for two model fields -
i have simple quiz model, , trying let user select correct answer/alternative answer 2 radio buttons, grouped , in typed view. lambda expressions use aren't working. 2 blank radio buttons. have looked @ several questions here, , online model ilist<>, , can't find suitable example. examples found work non-ilist<>.
this model
model:
public partial class question { public int questionid { get; set; } public string questionbody { get; set; } public string correctanswer { get; set; } public string alternativeanswer { get; set; } } my controller
public actionresult index() { quizsimpleentities quizentities = new quizsimpleentities(); var questions = p in quizentities.questions select p; return view(questions.tolist()); } my model:
@model ilist<quiz.models.question> <h2>welcome quiz</h2> @html.beginform(method:formmethod.post,controllername:"home",actionname:"index") { @foreach (var questions in model) { <p>@questions.questionbody</p> @* how display correctanswer , alternativeanswer 2 radio buttons grouped here? posting selected value } }
thank you
you need have property on view model hold selected answer when form posted:
public partial class question { public int questionid { get; set; } public string questionbody { get; set; } public string correctanswer { get; set; } public string alternativeanswer { get; set; } public string selectedanswer { get; set; } } and loop through elements of model , generated desired markup:
@model ilist<quiz.models.question> <h2>welcome quiz</h2> @html.beginform( method:formmethod.post, controllername:"home", actionname:"index") { @for (var = 0; < model.count; i++) { @html.hiddenfor(x => x[i].questionid) <fieldset> <legend> @html.displayfor(x => x[i].questionbody) </legend> <ul> <li> @html.hiddenfor(x => x[i].correctanswer) @html.radiobuttonfor(x => x[i].selectedanswer, model[i].correctanswer) @html.displayfor(x => x[i].correctanswer) </li> <li> @html.hiddenfor(x => x[i].alternativeanswer) @html.radiobuttonfor(x => x[i].selectedanswer, model[i].alternativeanswer) @html.displayfor(x => x[i].alternativeanswer) </li> </ul> </fieldset> } <button type="submit">ok</button> } note: when form submitted post action take ilist<question> model have answers each question (in selectedanswer property).
Comments
Post a Comment