ajax post always sends null parameter to my controller

jade duran 0 Reputation points
2024-03-21T10:48:26.3966667+00:00

HTML:

@{

ViewBag.Title = "exrcise3_usingJqueryPost";

}

<h2>Personal Information</h2>

Enter first name:

<input type="text" id="fname" />

<br />

Enter last name:

<input type="text" id="lname" />

<br />

<br />

<select id="sel_gender">

<option selected disabled> Select Gender</option>

<option value="0">Female</option>

<option value="1">Male</option>

<option value="2">LGBTQ</option>

</select>

<br />

Course <select id="sel_course">

<option selected disabled>Select Course</option>

<option value="0">BSIT</option>

<option value="1">BSED</option>

<option value="2">BSMT</option>

</select>

<br />

<br />

Gender:

<input type="radio" id="female" name="gender" value="0" />

Female

<br />

<input type="radio" id="male" name="gender" value="1" />

Male

<br />

<input type="radio" id="LGBTQ" name="gender" value="3" />

LGBTQ

<br />

<br />

<input type="button" id="btn" value="Submit" />

<script src="~/Scripts/srcps/jquery-3.7.1.min.js"></script>

<script src="~/Scripts/srcps/addGender.js"></script>

**JS
**
$(document).ready(function () {

$("#btn").click(function () {

    var lastname = $("#lname").val();

    var firstname = $("#fname").val();

    var value = $("input[name='gender']:checked").val();

    if (value == "0") {

        alert(firstname + " " + lastname + " Female");

    }

    else if (value == "1") {

        alert(firstname + " " + lastname + "Male");

    }

    else {

        alert(firstname + " " + lastname + "Other");

    }

    $.post('../Home/AddAjaxE', {

        lname: lastname,

        fname: firstname,

        gender: value,

    }, function (data) {

        if (data[0].mess == 0) {

            alert("Successfully saved!");

        }

        else {

            alert("Something missing!");

        }

    });

});

});

**CONTROLLER:
**
public ActionResult exrcise3_usingJqueryPost()

    {

        var data = new List<object>();

        var lastname = Request["lname"];

        var firstname = Request["fname"];

        data.Add(new

        {

            mess = 1

        });

        return Json(data, JsonRequestBehavior.AllowGet);

    }  

and the output is always:
ps. this code works on the other laptops and pc

[{"mess":1}]
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,255 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,250 questions
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 26,201 Reputation points
    2024-03-21T12:30:01.1933333+00:00

    ps. this code works on the other laptops and pc

    I'm not sure how your code works on other laptops when the AJAX post is calling URL "../Home/AddAjaxE" but the action is named exrcise3_usingJqueryPost(). Are you sure you shared the correct code?

    Home Controller

    public IActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public IActionResult exrcise3_usingJqueryPost(string lname, string fname, string gender)
    {
        return Json(new { lname = lname, fname = fname, gender = gender });
    }
    

    View

    @{
        ViewData["Title"] = "Index";
    }
    <h2>Personal Information</h2>
    Enter first name:
    <input type="text" id="fname" />
    <br />
    Enter last name:
    <input type="text" id="lname" />
    <br />
    <br />
    <select id="sel_gender">
        <option selected disabled> Select Gender</option>
        <option value="0">Female</option>
        <option value="1">Male</option>
        <option value="2">LGBTQ</option>
    </select>
    <br />
        Course
    <select id="sel_course">
        <option selected disabled>Select Course</option>
        <option value="0">BSIT</option>
        <option value="1">BSED</option>
        <option value="2">BSMT</option>
    </select>
    <br />
    <br />
        Gender:<br />
    <input type="radio" id="female" name="gender" value="0" />
        Female
    <br />
    <input type="radio" id="male" name="gender" value="1" />
        Male
    <br />
    <input type="radio" id="LGBTQ" name="gender" value="3" />
        LGBTQ
    <br />
    <br />
    <input type="button" id="btn" value="Submit" />
    @section scripts{
        <script>
            $("#btn").click(function () {
                var lastname = $("#lname").val();
                var firstname = $("#fname").val();
                var value = $("input[name='gender']:checked").val();
                if (value == "0") {
                    console.log(firstname + " " + lastname + " Female");
                }
                else if (value == "1") {
                    console.log(firstname + " " + lastname + "Male");
                }
                else {
                    console.log(firstname + " " + lastname + "Other");
                }
                $.post('/Home/exrcise3_usingJqueryPost', {
                    lname: lastname,
                    fname: firstname,
                    gender: value,
                }, function (data) {
                    console.log(data);
                });
            });
        </script>
    }
    

    I recommend going through a few getting started tutorials to learn basic MVC programming patterns.

    https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started

    0 comments No comments

  2. Bruce (SqlWork.com) 56,026 Reputation points
    2024-03-21T16:51:44.04+00:00

    the response matches the code:

     {
            var data = new List<object>();
            var lastname = Request["lname"];  // never used
            var firstname = Request["fname"]; // never used
    
            data.Add(new
            {
                mess = 1
            });
    
            return Json(data, JsonRequestBehavior.AllowGet);
      }  
    

    as list is returned as a json array. you added one item to the list that had one property mess = 1. so you returned an array with one item.

    [{"mess":1}]

    try:

            data.Add(new
            {
                firstname = Request["fname"],
                lastname = Request["lname"],
                mess = 1
            });
    

    or

        return Json(new {lastname,firstname,data}, JsonRequestBehavior.AllowGet);
    
    0 comments No comments

  3. Lan Huang-MSFT 25,556 Reputation points Microsoft Vendor
    2024-03-22T02:14:55.71+00:00

    Hi @jade duran,

    There are several issues with your code.

    1.The POST URL should be: $.post('../Home/exrcise3_usingJqueryPost', {

    2.You assigned mess as 1, but the "Successfully saved!" message pops up when data[0].mess == 0 is judged in JS. This is unreasonable.

    You can tell data[0].mess == 1.

    if (data[0].mess == 1) {
        alert("Successfully saved!");
    }
    

    3.The lastname and firstname you defined are not used.

     [HttpPost]
     public ActionResult exrcise3_usingJqueryPost()
     {
         var data = new List<object>();
         var lastname = Request["lname"];
         var firstname = Request["fname"];         
         data.Add(new
         {              
             firstname =firstname,
             lastname = lastname,              
             mess = 1
         });
         return Json(data, JsonRequestBehavior.AllowGet);
     }
    
    
    $(document).ready(function () {
        $("#btn").click(function () {
            var lastname = $("#lname").val();
            var firstname = $("#fname").val();
            var value = $("input[name='gender']:checked").val();
            if (value == "0") {
                alert(firstname + " " + lastname + " Female");
            }
            else if (value == "1") {
                alert(firstname + " " + lastname + "Male");
            }
            else {
                alert(firstname + " " + lastname + "Other");
            }
            $.post('../Home/exrcise3_usingJqueryPost', {
                lname: lastname,
                fname: firstname,
                gender: value,
            }, function (data) {
               // alert("lastname:" + data[0].lastname + " " + "firstname:" + data[0].firstname);         
                if (data[0].mess == 1) {
                    alert("Successfully saved!");
                }
                else {
                    alert("Something missing!");
                }
            });
        });
    });
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments