Share via


Retrieve data to view from stored procedure by using ajax in MVC

Question

Wednesday, August 16, 2017 6:34 AM

I am trying to retrieve data into table by using stored procedure using ajax.

My controller code is: 

it does not go under the while condition to read the data when I submit the no of students. 

string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            List<dynamic> list = new List<dynamic>();
            List<SqlParameter> parameters = new List<SqlParameter>();

            parameters.Add(new SqlParameter("@NoOfStudents", model.noofStudents));

            using(var connection=new SqlConnection(connectionString))
            {
                using(var reader = SqlHelper.ExecuteReader(connection, System.Data.CommandType.StoredProcedure, "BSMeritCalculator", parameters.ToArray()))
                {
                    while(reader.Read())
                    {
                        var Merit = CheckIntegerNull(reader["Merit"]);
                        var FormNo = CheckIntegerNull(reader["FormNo"]);
                       // var DiaryNo = CheckIntegerNull(reader["DiaryNo"]);
                        var Name = CheckStringNull(reader["Name"]);
                        var Status = CheckIntegerNull(reader["Status"]);

                        list.Add ( new { Merit = Merit,
                                       FormNo = FormNo,
                                       Name = Name,
                                       Status = Status });

                    }
                }
            }
            return Json(list, JsonRequestBehavior.AllowGet);

my View and Ajax Code is:

@using (Html.BeginForm())
{
    <table cellspacing="20" >
        <tr>
            <td>No of Students :</td>
            <td>
                <span class="input-icon">
                    @Html.TextBox("noOfStudents", "", new { @id = "noOfStudents" })<i class="ace-icon fa fa-search nav-search-icon"></i>
                    <i class="ace-icon fa fa-search nav-search-icon"></i>
                </span>
            </td>
            <td>
                <button class="btn btn-xs btn-yellow active" type="submit" name="Generate" value="Generate" 
                id="btnGenerate">
                    <i class="ace-icon fa fa-check bigger-110"></i>
                    Generate Merit
                </button>
            </td>
        </tr>
    </table>
}

<script>

$(document).ready(function () {
            $("#btnGenerate").on("Click", function () {
                var NoOfStudents = $("#noOfStudents").val();
                
                alert(NoOfStudents);

                var MeritList = {
                    "No of Students": noOfStudents
            };
            
            $.ajax({
                url: '@Url.Action("GenerateMerit", "Student")',

                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(MeritList),
                type: 'POST',
                success: function( data )
                {
                    GenerateMerit(data);
                },
                error: function(){
                    alert("Merit List Not Generated")
                }
            });
            
            });
        });

        function GenerateMerit(data) {

            //clear result div
            $("#container").html("");
            var table = ("<table id=DynamicTable border=1></table>").appendTo("#container");

            var dataObj = [];
            if(data && data.length > 0)
            {
                for(var i = 0; i < data.length; i++)
                {
                    var obj = data[i];
                    //dataObj.push([obj.Name, obj.FormNo, obj.Merit]);

                    //create table header row
                    var rowHeader = $("<tr></tr>").appendTo(table);
                    $("<td></td>").text("Name").appendTo(rowHeader);
                    $("<td></td>").text("Form No").appendTo(rowHeader);
                    $("<td></td>").text("Merit %").appendTo(rowHeader);

                    //get table data from row
                    var row = $("<tr></tr>").appendTo(table);
                    $("<tr></td>").text(obj.Name).appendTo(row);
                    $("<tr></td>").text(obj.FormNo).appendTo(row);
                    $("<tr></td>").text(obj.Merit).appendTo(row);
                }
            }
        }
    </script>
    

Kindly guide me what I did wrong

All replies (6)

Tuesday, August 22, 2017 5:36 AM âś…Answered

Hi Ridzi,

I find that there is something wrong with your JavaScript code. I think it may be the reason.

1. The 'c' of 'click' should be lower-case. The function name of JavaScript is case sensitive.

$("#btnGenerate").on("click", function (event) {}

2. Modify '"No of Students": noOfStudents' to '"No of Students": NoOfStudents'.

3.Modift '$("<tr></td>").text' to '$("<td></td>").text' in GenerateMerit function.

Here is my code, you can take it as a reference.

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>

    $(document).ready(function () {
        $("#btnGenerate").on("click", function (event) {
            event.preventDefault();
            var NoOfStudents = $("#noOfStudents").val();

            //alert(NoOfStudents);

            var MeritList = {
                "No of Students": NoOfStudents
            };

            $.ajax({
                url: '@Url.Action("GenerateMerit", "Student")',

                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(MeritList),
                type: 'POST',
                success: function( data )
                {
                    GenerateMerit(data);
                },
                error: function(){
                    alert("Merit List Not Generated")
                }
            });
        });

    });

    function GenerateMerit(data) {

        //clear result div
        $("#container").html("");
        var table = $("<table id=DynamicTable border=1></table>").appendTo("#container");

        var dataObj = [];
        if (data && data.length > 0) {
            //create table header row
            var rowHeader = $("<tr></tr>").appendTo(table);
            $("<td></td>").text("Name").appendTo(rowHeader);
            $("<td></td>").text("Form No").appendTo(rowHeader);
            $("<td></td>").text("Merit %").appendTo(rowHeader);
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                //dataObj.push([obj.Name, obj.FormNo, obj.Merit]);



                //get table data from row
                var row = $("<tr></tr>").appendTo(table);
                $("<td></td>").text(obj.Name).appendTo(row);
                $("<td></td>").text(obj.FormNo).appendTo(row);
                $("<td></td>").text(obj.Merit).appendTo(row);
            }
        }
    }
</script>

Best Regards,

Jean


Thursday, August 17, 2017 9:30 AM

Hi Ridzi,

it does not go under the while condition to read the data when I submit the no of students. 

Your code is correct, please note that if the Store procedure doesn't return any record it will skip while loop.

Please try execute the store procedure with the student no in the SQL Server Management Studio to check if the store procedure return any record.

Best Regards,

Jean


Thursday, August 17, 2017 10:14 AM

Hi Jean, 

Your code is correct, please note that if the Store procedure doesn't return any record it will skip while loop.

Thanks for your reply, I have resolved this issue but the list show on view as 

[{"Merit":151,"FormNo":1111,"Name":"xyzabc","Status":0}]

Kindly help me if you have any idea.


Friday, August 18, 2017 8:31 AM

Hi Ridzi,

It's because you set the type of the btnGenerate to submit. When you click that button, it will submit the form and then the page will be refreshed. There are two methods to solve it.

1. Modify type="submit" to type="button", then the button will not submit form when click it.

<button class="btn btn-xs btn-yellow active" type="button" name="Generate" value="Generate" id="btnGenerate">
    <i class="ace-icon fa fa-check bigger-110"></i>
    Generate Merit
</button>

2. Use preventDefault method in Jquery

$("#btnGenerate").on("click", function (event) {
            event.preventDefault();
}

This method notifies the Web browser not to perform the default actions associated with the event (if such action exists). For example, if the type attribute is 'submit',  the submission form can be blocked by invoking this method.

Best Regards,

Jean


Friday, August 18, 2017 10:03 AM

Hi Jean,

Thanks for your reply.

1. Modify type="submit" to type="button", then the button will not submit form when click it.

2. Use preventDefault method in Jquery

Jean I am still getting the same view result.


Tuesday, August 22, 2017 11:30 AM

Hi Jean,

I find that there is something wrong with your JavaScript code. I think it may be the reason.

I also change this line because after changing button type it does not go to the controller

url: '/Student/GetMerit',

Thanks for your help