locked
null in controller but sending value in fine in view. MVC RRS feed

  • Question

  • User-240513752 posted

    Index

        <a onclick="OnDetails('@item.StudentId')"> Details by Anchor </a>

    javascript

    <script type="text/javascript">
        function OnDetails(id) {
            alert((typeof 42) + id);
            $.ajax({
                url: '@Url.Action("DetailsonAnchor" ,"Student")',
               // url: "Student/DetailsonAnchor/",
                dataType: "json",
                data:  id  ,
                type: "GET",
                //contentType: 'application/json; charset=utf-8',
                cache: false,
               
            success: function (data) {
                if (data.success) {
                    alert(data.message);
                }
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
            return true;
        }
    </script>

    Controller

     [HttpGet]
            public ActionResult DetailsonAnchor(int? id) //Here Id is getting null in controller
            {
                if (!id.HasValue)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                StudentModel model = db.Student.Find(id);
                if (model == null)
                    return HttpNotFound();
    
                return View(model);
            }

    Here Id is getting null in controller even it is showing the value of integer while sending it from javascript.

    Sunday, April 26, 2020 11:23 AM

Answers

  • User475983607 posted

    The syntax error is very clear if you learn how to take advantage of the Network trace tool in the bower's dev tools. 

    It also help if you read the jQuery docs as it explains the AJAX options and shows examples of the formatting.

            function OnDetails(id) {
                $.ajax({
                    url: '@Url.Action("DetailsonAnchor" ,"Home")',
                    dataType: "json",
                    data: { 'id': id },
                    type: "GET",

    You can also take advantage of default MVC routing.

            function OnDetails(id) {
                $.ajax({
                    url: '@Url.Action("DetailsonAnchor" ,"Home")/' + id,
                    dataType: "json",
                    type: "GET",
                    cache: false,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, April 26, 2020 12:51 PM