I need to modify a JavaScript function that retrieves a value from a textbox depending on the selected Radio button.
For example: If the Radio button No is selected, the value is retrieved from TextBox A. However, if the Radio button Yes is selected, the value is taken from TextBox B. Below is the script in my view:
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
if (document.getElementById('RadioNo').checked) { // ID of radio button NO
var checking = $('#Donation').val(); // ID of textbox to retrieve value from if Radio button No is selected
if (checking == "") {
// If nothing is entered, prevent saving in DB
} else {
x = $('#Donation').val(); // ID of textbox to retrieve value from if Radio button No is selected
$.ajax({
url: '@Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
} else {
x = $('#GetNames').val(); //ID of textbox to retrieve value from if Radio button Yes is selected
$.ajax({
url: '@Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
});
It seems to be working correctly up to this point. Now, in the controller, I have a function called DonationValue
.
Question:
- How can I pass the
name
parameter mentioned above? - If no value is entered in the TextBox with the ID #Donation, how can I prevent saving the form in the database?
My Attempt:
I have tried the following:
public string DonationValue(string name = null)
{
return name; // Attempting to pass this value mentioned above
}
Although this removed the error, the passed value was always null. I have tried other methods as well, but none have been successful.
Edited:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = _DonationValue
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
return // something to save state so that the user doesn't have to enter all the values again
}
[HttpPost]
public void DonationValue(string name)
{
_DonationValue = name;
}