简体   繁体   中英

Loading selected radio buttons using an editor c#

In relation to this question:

StackOverflow - Grouping radio buttons in c# mvc

I have managed now to load and save the selected options from the form into a database but now the user may need to edit this.

How do I load the view with the selected user's choices? I cannot see where you can set selected Answer. On load I am getting the default values selected

用这个:

<%= Html.RadioButtonFor(m => m.Something, "something", new { Checked = "checked" })%>

You can set the SelectedAnswer property value for each Course in your GET action and your EditorTemplate will take care of the rest.

public ActionResult Index()
{
    var vm= new OrderViewModel();

    //the below is hard coded for DEMO. you may get the data from some  
    //other place and set the course and options

    var q1 = new Course { ID = 1, Name= "Starters" };
    q1.Options.Add(new Option{ ID = 12, Title = "Prawn Cocktail " });
    q1.Options.Add(new Option{ ID = 13, Title = "Soup" });
    q1.SelectedAnswer = 13; //to do : get the selected answer value from DB

    vm.Courses.Add(q1);     

    var q2 = new Course { ID = 1, Name= "Mains" };
    q2.Options.Add(new Option{ ID = 42, Title = "Beef" });
    q2.Options.Add(new Option{ ID = 43, Title = "Lamp" });
    q2.SelectedAnswer = 16;// to do :get the selected answer value from DB

    vm.Courses.Add(q2);

   return View(vm);           
}

There is no change to be made to your editor template. It stays same as the previous answer.

@model Course
<div>
    @Html.HiddenFor(x=>x.ID)
    <h3> @Model.Name</h3>
    @foreach (var a in Model.Options)
    {
       <p>
          @Html.RadioButtonFor(b=>b.SelectedAnswer,a.ID)  @a.Title
       </p>
    }
</div>

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