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:
Treat your CREATE view the same you would do an UPDATE view. You should add Razor syntax for any radiobuttons that should be clicked.
You should use either Razor or Javascript to figure out which dynamic contents to show or hide based on the selected radio buttons.
Related
I am wanting to redirect to another page but at the same time being able to grab the details of the button that was selected. I was reading up on how onsubmit works with HTML and radio buttons work. Prior to adding buttons, I had a button and whenever it was clicked it would redirect me to the next page. I still want to do the same thing, just being able to add radio buttons to the view and submit that radio button so that way I can grab the information from the button that was selected.
I attempted:
#{
ViewData["Title"] = "Index";
}
<h2>Customer</h2>
<form method="POST">
<input type="radio" value="1" /><label>Valid</label>
<input type="radio" value="2" /><label>Wrong</label>
<input type="radio" value="3" /><label>InValid</label>
<a href="#("window.location.href='" + #Url.Action("SecIndex", "Second") + "'");">
<input type="submit" value="Address Validation" />
</a>
However, this does not redirect me to the page that I needed it to redirect to. I also noticed that once I select buttons I cannot unselect, is that apart of the radio button feature?
I also noticed that once I select buttons I cannot unselect, is that apart of the radio button feature
Yes. That's how it works.
I still want to do the same thing, just being able to add radio buttons to the view and submit that radio button so that way I can
grab the information from the button that was selected.
If you want to post the selected value to backend, you could set name for radio buttons. Because model binding system will bind value by name.
View:
<form method="POST" asp-action="SecIndex" asp-controller="Second">
<input type="radio" value="1" name="Status"/><label>Valid</label>
<input type="radio" value="2" name="Status"/><label>Wrong</label>
<input type="radio" value="3" name="Status"/><label>InValid</label>
<input type="submit" value="Address Validation" />
</form>
Controller:
public class SecondController : Controller
{
[HttpPost]
public IActionResult SecIndex(string Status)
// you can get "1" or "2" or "3" which based on your checked radio button
{
return RedirectToAction("Privacy");
}
}
HTML doesn't have store capability. you can't grab data without a programming language. But you can click to redirect to another page.
Use the button tag and use the anchor tag in the button, rather than -
Please, I'm stuck trying to send my radio button user choice to the aspx.cs file and sent it to SQL, so here's the code:
<div class="form-group">
<label class="control-label col-sm-3">Status</label>
<div class="col-sm-6">
<div class="row" id="row" runat="server">
<div class="col-sm-4">
<label class="radio-inline">
<input type="radio" id="nsent" value="nsent" name="status" runat="server" checked="true">Not Sent
</label>
</div>
<div class="col-sm-4">
<label class="radio-inline">
<input type="radio" id="sent" value="sent" name="status" runat="server">Sent
</label>
</div>
</div>
</div>
So after I click Submit, there's a code to send it to SQL, but I don't have any idea how I would send the value selected in the HTML.
Selected Item or Selected Value won't work, even InnerText.
for a radio button, and in WEBFORMS, you would look at both control's CHECK state
if (sent.Checked) == true {...}
if (nsent.Checked == true) {...}
Alternatively you could review the FORMS collection that was submitted with the Page.Request (if this is a POSTBACK).
if (page.request.forms["status"] == "sent") {
...
} elseif (page.request.forms["status"] =="nsent" {
...
}
A third option, which seems to be outside the scope of your question is to read the radio buttons on the client side, and submit the value to the server via some AJAX style submission.
You should use <asp:Checkbox> (ASP.NET WebForms) or #Html.CheckBoxFor() (ASP.NET MVC).
So I've got this popup in my site with a list of checkboxes for filtering purposes. The List can be anywhere from a couple items to a hundred items. Now say the user wants to only select check boxes with the word "create" in it's label. Going through a hundred check boxes looking for creates is unruly and no ones going to want to do it. What I'm thinking is implementing a text box input at the bottom of the popup where the user can input a word, hit select and in the list of checkboxes, only the items that contain that word will be checked.
The first idea that came to mind to do this is use jquery have the button relate to a controller function which will reassess the view model based on that users string. But I'm not if that the best solution. Is there a way to do this in just the view?
Try something like this:
Your HTML:
<div class="box">
<input type="checkbox" name="check">
<label>Create</label>
</div>
<div class="box">
<input type="checkbox" name="check">
<label>Other value</label>
</div>
<div class="box">
<input type="checkbox" name="check">
<label>Create user</label>
</div>
Your JQuery code:
$(function(){
$('.box').each(function(){
var box = $(this);
if ($('label', box).html().toLowerCase().indexOf("create") > 0) {
$('input[type=checkbox]', box).attr('checked', 'checked');
}
else $('input[type=checkbox]', box).removeAttr('checked');
});
});
This is a better solution suggested by #AnoopJoshi
$("label:contains('Create')").closest(".box").find("input[type=checkbox]").prop("checked", true);
I hope this help!
This question already has answers here:
How do you handle multiple submit buttons in ASP.NET MVC Framework?
(35 answers)
Closed 9 years ago.
This code was working at one point. I'm not sure what broke it, but basically on postback I'm looking for the existence of a submit button key in the FormsCollection. Depending on the existence, I perform different operations. The custom attribute to handle this is getting hit. When I step through it and look at the FormsCollection, I can see all key/values from the form except for the submit button which submitted the form.
Looking at the submission via Fiddler2, it doesn't even look like the submit button is being sent to the server with the rest of the values. If I put in a hidden field with the same name I am looking for (and hard coded value) I can successfully hit the "if exists" logic branch because the hidden field's value is sent to the server.
Here's my form:
#using (Html.BeginForm("Respond", "AccountInvitations", new {id = Model.Invitation.InvitationCode, ReturnUrl = Request.QueryString["ReturnUrl"] ?? string.Empty}, FormMethod.Post, new {#class = "invitation-details-form"}))
{
<div class="modal-body">
<div class="status-message info">
<i></i>
You have been invited to join <strong>#Model.Invitation.AccountName</strong>.
Create your profile below to join this account.
</div>
#Html.AntiForgeryToken()
#Html.ServerValidationSummary()
#Html.EditorFor(model => model.InvitationResponse, "InvitationResponseDto", "")
</div>
<div class="modal-footer">
<div class="button-container clearfix">
<input type="submit" name="accept" value="Accept Invitation" class="btn btn-secondary" />
<input type="submit" name="decline" value="Decline Invitation" class="btn btn-link cancel" />
</div>
</div>
}
Neither "accept" nor "decline" shows up in the FormsCollection when I press on either (the form is submitted and all fields from the editor template show, but not the submit inputs).
I do not want to handle this with javascript setting a hidden field value.
Wow, it's been a long couple nights coding. This post led me to the answer. A couple weeks back a script was added to prevent double clicking on some form entries. The form disabled the inputs immediately upon form submission. A simple setTimeout() to delay the disabling did the trick.
OR you can using
<div class="modal-footer">
<div class="button-container clearfix">
#using (Html.BeginForm("Your_ActionResult", "Your_controller"}, FormMethod.Get/Post))
{
#Html.AntiForgeryToken()
<input type="submit" name="accept" value="Accept Invitation" class="btn btn-secondary" />
}
#using (Html.BeginForm("Your_ActionResult", "Your_controller"}, FormMethod.Get/Post))
{
#Html.AntiForgeryToken()
<input type="submit" name="decline" value="Decline Invitation" class="btn btn-link cancel" />
}
</div>
</div>
you must specify the submit button that call the ActionResul method in your Controller is
I'm trying to figure out how to get my Javascript code to check whether or not a button has been chosen. If it has, I would like to display the button's value.
I have the following HTML:
<li class="control-group">
<label for="amount" class="control-label">Select an amount</label>
<div class="controls">
<div class="btn-group radioButtons amountButtons" data-toggle="buttons-radio">
#if (Model.PresetValues.Count > 0){
foreach (int value in Model.PresetValues) {
<button type="button" data-value="#value" class="btn #(Model.chargeViewModel.ChargeAmount == value ? "active" : "")">$#value</button>
}
}
<button type="button" data-value="other" class="btn toggleDiv toggleOnce" data-toggle-id="#manualAmount">Other</button>
</div>
<input type="hidden" class="radioHidden validate required validateAmount" value="" id="amount" name="ChargeAmount">
</div>
<div class="controls hide resize" id="manualAmount">
<div class="input-prepend input-append">
<button class="btn minus" type="button"><i class="icon-minus"></i></button>
<input class="span2 plusminus" data-max="100" data-min="10" data-increment="5" data-value="25" id="manualAmountInput" type="text" value="$25" disabled>
<button class="btn plus" type="button"><i class="icon-plus"></i></button>
</div>
</div>
</li>
Those are my two options for the button and I would like to edit the following span
<span class="help-block">Your card will automatically reload $<span id="autoAmount">0</span> when your balance is lower than your reload threshold.</span>
I have the following script which I was led to believe will change the value of the span as it is clicked, but I am having a difficult time connecting them together.
<script>
javascript: void (document.getElementById("autoAmount").innerHTML = amount);
</script>
if anyone has any suggestions or ideas, it would be greatly appreciated.
Thanks!
To expand on kyllo's answer a little bit...
First you would need to bind a click event to your button. You can set it as an onClick attribute:
<input type="button" onClick="captureAmount(e); return false;">
Including the 'e' inside captureAmount will pass the click event itself over to our function, which we can use to figure out which button was clicked (if you are using this function in more than one place).
You can also use jQuery if you've included that library, to attach the function to every button on the page at once.
$('input[type=button]').click(captureAmount(e));
Or, specify buttons with a particular class..
$('input.amountBtns').click(captureAmount(e));
And your function could look a little something like this:
function captureAmount(e){
var clicked = e.target
, clickedAmount = clicked.value
, display = document.getElementById("autoAmount")
;
display.innerHTML = clickedAmount;
}
If you want the innerHTML of the autoAmount span to change when you click a button, then you would need to bind an onclick event to that button, and then when the onClick event fires, you would do document.getElementById("autoAmount").innerHTML = amount.value
for example, in the button declaration you can add
onclick="updateAmount()"
and then inside the script tags you would declare a javascript function that is called by the onclick event:
function updateAmount(){
document.getElementById("autoAmount").innerHTML = document.getElementById("amount").value
}
(Keep in mind that your "amount" input box is hidden, though.)