What should you do if the Optional Parameter concept is not functioning as expected?

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:

  1. How can I pass the name parameter mentioned above?
  2. 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;
}

Answer №1

@Daisy Shipton. Do you think this solution is more effective?

<script>
        $(function() {
            $('#btnVolunteerSaveBtn').on('click', function() { // handle save button click event
                debugger;
                if (document.getElementById('RadioNo').checked) { // check if radio button 'NO' is selected
                    var checking = $('#Donation').val(); // get value from textbox if 'NO' is selected
                    if (checking == "") {
                        // prevent saving in DB if no value entered
                    }
                    else {
                        var x = $('#Donation').val(); // get value from textbox if 'NO' is selected
                        var jsonObject = {
                            "textValue": x,
                            "isRadioSelected": "true" // indicate radio selection
                        };

                        $.ajax({
                            url: '@Url.Action("AddVolunteer", "VolunteerInfo")',
                            data: JSON.stringify(jsonObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            type: "POST",
                            error: function (response) {
                                alert(response.responseText);
                            },
                            success: function (response) {
                                alert(response);
                            }
                        });
                    }
                }
                else {
                    var jsonObject2 = {
                        "textValue": $('#GetNames').val(),
                        "isRadioSelected": "false" // indicate radio not selected
                    };

                    $.ajax({
                        url: '@Url.Action("AddVolunteer", "VolunteerInfo")',
                        data: JSON.stringify(jsonObject2),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        type: "POST",
                        error: function (response) {
                            alert(response.responseText);
                        },
                        success: function (response) {
                            alert(response);
                        }
                    });
                }

            });
        })
    </script>

In the controller:

[HttpPost]
    public ActionResult AddVolunteer(VolunteerInfo volunteerInfo)
    {
        if (volunteerInfo.isRadioSelected)
        {
            // handle selection
        }
        else
        {
           // handle unselection
        return View();
    }

Answer №2

1) The DonationValue post method is called by the client with a name parameter

For example, name="abc"

[HttpPost]
public string DonationValue(string name = null)  // name = "abc"
    {
        return name; //Attempting to pass this value above
    }

This returned value will be stored on the client side as a variable named retunedDonationValue

If no name parameter is passed, the above post method will return an empty string, so just set retunedDonationValue = ''

2) Now you need to pass the above retunedDonationValue to your post method in the posted JSON object like this:

var jsonObject = 
                {
                    "Name" = "YourName",
                    "BirthdayDateTime" = "YourBirthdayDateTime",
                    "Address" = "YourAddress",
                    "PhoneNumber" = "YourPhoneNumber",
                    "EmailAddress" = "YourEmailAddress",
                    "OccasionsID" = "YourOccasionsID",
                    "DonationForWhom" = retunedDonationValue  //Note here
                }

3) Then pass this post data to the http call to AddVolunteer

                    $.ajax({
                        url: '@Url.Action("AddVolunteer", "VolunteerInfo")',
                        data: JSON.stringify(jsonObject),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        type: "POST",
                        error: function (response) {
                            alert(response.responseText);
                        },
                        success: function (response) {
                            alert(response);
                        }
                    });

4) The action method looks like this:

[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 = viewModel.DonationForWhom
        };

        if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
        {
            _context.VolunteerInfos.Add(volunteer);
            _context.SaveChanges();
        }

        return View(viewModel);

    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Backward and Forward Navigation with AJAX, JavaScript, and Window.History

TARGET Implement Ajax for fetching pages Utilize JavaScript to update the window URL Leverage Window History to preserve Ajax page for seamless forward-backward navigation without reloading the page Modify the Navigation bar's attributes (such as co ...

An error occurred: TypeError - Unable to access the 'value' property of a null object during a value change

Example ImageCreating a dynamic form where rows and select box options are added dynamically using 'x' and 'i' increment values in two JavaScript functions. The code works fine when the option selected is 0.5, but throws an error Uncaug ...

Vuejs v-for nested loops

After spending countless hours researching, I am determined to solve this problem. My objective is to create a questionnaire similar to a Google Form, with question groups, questions, and answers. The structure of my data looks like this: question_group: ...

Scope of MongoDB's `.findOne` method

Having trouble with variable scope. var max; ClassModel.findOne({ class: '1a' }, function (err, class1a) { if (err) return handleError(err); max = class1a.members; console.log(max); }); console.log(max); Why does ...

Is it possible to replace dependent assemblies in .NET without having to recompile the

Seeking clarification on how the .NET framework (2.0) handles dependent assemblies. We are currently in the process of revamping a significant ASP.NET application along with multiple satellite executables. Additionally, there are some persistent issues wi ...

Discover the worth within the outcome obtained from the AJAX request

I have an action that returns a tuple containing a boolean value and a string. How can I retrieve the first boolean value from the result, which could be either true or false? This is the action: public Tuple<bool, string> Check This is the AJAX c ...

unable to send updates to groups in socket.io

When a user connects, the system will search for a room with fewer people than the maximum allowed. If such a room is found, the user joins it. If no suitable room is available, the system creates a new one. The room creation process is functioning correct ...

Having difficulty displaying a partial view within a view while making an AJAX call

Trying to figure out what's missing in my code. I have a view with some radio buttons and I want to display a different partial view when a radio button is selected. Here's the snippet of my code: Controller public ActionResult Method(string va ...

Use jQuery to swap out images and witness the image loading in real time

Currently, I am using jQuery to dynamically change images by using the code $('img').attr('src','newUrl'); However, whenever I do this, the image is only displayed once it has completely loaded. Due to my slow internet conne ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

Identifying periods of inactivity using an embedded iframe

I have developed a website that showcases a three.js model within an iframe. My goal is to redirect users back to the homepage (index.html) after they have been inactive for a specified amount of time. While I have managed to achieve this using JavaScript, ...

What steps should be taken to develop a Hybrid Mobile App concept?

We are currently developing our first hybrid mobile application with a monetizable idea in mind. After conducting some research, it seems that to reach our end goal we will need: A Front End UI Framework: options include Ionic or AngularGap (although d ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

The 'in' operator in JQuery is unable to search for 'length' when using an Ajax response

[{"ContainerNo":"FCIU3554053","Size":20,"SealNo":"172003","Weight":25209.00},{"ContainerNo":"TEMU5422909","Size":20,"SealNo":"164169","Weight":25400.00}] $.ajax({ url: "/Popu/GetContainers", dataType: "json", complete: function (res ...

Determine whether an element has the capability to hold text content

Is there a surefire and reliable method to determine if an HTML element is capable of holding text, using only pure JavaScript or jQuery? For example, <br>, <hr>, or <tr> cannot contain text nodes, whereas <div>, <td>, or < ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

Update a JavaScript variable with fresh information and then execute JSON parsing

I have implemented this code to display a Verite Timeline on my webpage: <div id="timeline-embed"></div> <script type="text/javascript"> var timeline_config = { width: "100%", height: "100%", debu ...

What could be causing the visibility issue with my navigation items in the bootstrap navigation bar?

Currently, I am experiencing a puzzling issue with the navigation bar on my live website. The navigation items seem to flicker for a brief moment and then disappear entirely. This unexpected behavior is certainly causing me some concern. I crafted the us ...

Creating 3D models in three.js

Working with a 3D point cloud data in three.js, I have successfully added points to a Geometry using Vector3. Now I am looking to create surfaces from these points. for(var key in dt) { var hole = dt[key]; var pX = hole['x'] - planeMinX; var pY ...

The detected coordinates are offset from the location of the mouse click

Seeking guidance: I need advice on an issue that arises when clicking on the second tooth from right to left, causing the upper teeth to be colored instead: https://i.sstatic.net/czzmc.png Below is a step-by-step explanation of what the code does: 1) T ...