简体   繁体   中英

How to keep radio buttons populated after postback

I have a page that has dynamic rows that show and hide based on radio button selection. There is also validation making sure that each field (that is shown) is populated and has a valid value. When the user submits the page it validates the fields and posts back and while the text box values are stored all the radio buttons become deselected and the dynamic rows are all hidden. I was wondering how to maintain the selection of the radio buttons and the visible/hidden fields after a postback.

<div class="form-group">
    <label asp-for="HaveYouEnteredTheProperty">Have you entered the property?</label>
    <div asp-for="HaveYouEnteredTheProperty" class="btn-group btn-group-toggle" data-toggle="buttons" style="width:100%">
        <label style="width:50%" class="btn btn-success">
            <input type="radio" name="VisitDetailsRadio" id="propYes" value="Yes"/> Yes 
        </label>
        <label style="width:50%" class="btn btn-danger">
            <input type="radio" name="VisitDetailsRadio" id="propNo" value="No" /> No 
        </label>
    </div>
    <span asp-validation-for="HaveYouEnteredTheProperty" class="text-danger"></span>
</div>

this is one of my radio buttons on the cshtml page

 $("input[name=VisitDetailsRadio]").change(function () {
    if ($(this).val() == "No") {
        $(".VisitDetailsExpandedYes").hide();
        $(".VisitDetailsExpandedNo").show();
        $(".EnteredProperty").hide();
    }
    else {
        $(".VisitDetailsExpandedYes").show();
        $(".VisitDetailsExpandedNo").hide();
        $(".EnteredProperty").show();
         }
});

This is the jquery that shows and hides fields based on the radio button selection

if (results.IsValid)
{
    _context.Results.Add(model);
    _context.SaveChanges();

    ModelState.Clear();
    return View();
}

else
{

    results.AddToModelState(ModelState, null);
    return View(model);
}

and this is the validation after pressing the submit button at the end of the form.

Any help would be appreciated.

On a high level, what you need to do is the following:

  1. Treat your CREATE view the same you would do an UPDATE view. You should add Razor syntax for any radiobuttons that should be clicked.
  2. You should use either Razor or Javascript to figure out which dynamic contents to show or hide based on the selected radio buttons.

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