Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi There,

I am new in jquery and mvc am using following html file having jquery to call
call MVC 4 web API.Web API function get called perfectly but I don't know how to show it in html page. Please help me how to show it in html page.

XML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
    $(document).ready(function () {
        $("button").click(function () {
            $.ajax({

                type: 'GET',
                dataType: 'json',
                cache: false,
                contentType: 'application/json; charset=utf-8',
                async: false,
                data: '{}',

                url: ' api/TestApi/GetProfiles',

                success: function (data) {
                    alert(data);
                    $("#tbDetails").append("<tr><td>" + data.d[0].userName + "</td><td>" + data.d[0].userRole + "</td></tr>");
                    for (var i = 0; i < data.d.length; i++) {
                        alert('hia');
                        $("#tbDetails").append("<tr><td>" + data.d[i].userName + "</td><td>" + data.d[i].userRole + "</td></tr>");
                    }
                },
                error: function (err) {
                    alert(err.message);
                }
            });
        });
    });
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Toggle between slide up and slide down for a p element</button>
 <table id="tbDetails" cellpadding="0" cellspacing="0">
<thead style="background-color:#DC5807; color:White; font-weight:bold">
<tr style="border:solid 1px #000000">
<td>userName</td>
<td>userRole</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>


Web API Code
C#
public class TestApiController : ApiController
{

    public  UserDetails[] GetProfiles()//[FromBody]Dictionary<string,>[] reqData)
    {
        DataTable dtuser = new DataTable();
        List<userdetails> details = new List<userdetails>();
        try
        {
            
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = "Data Source=175.41.138.226 , 3784;User ID=CEVA_GIPS;Password=D3fQMK3sJf23H;";
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT top 10 userName, userRole FROM  LIVE_BILLINGRATING..Users ";
                cmd.Connection = conn;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtuser);
                foreach (DataRow dtrow in dtuser.Rows)
                {
                    UserDetails user = new UserDetails();
                    user.UserId = dtrow["userName"].ToString();
                    user.UserName = dtrow["userRole"].ToString();
                   
                    details.Add(user);
                }
            
        }
        catch (Exception ex)
        {
            //return dt;
        }

        return details.ToArray();
        //return dt;
    }
    public class UserDetails
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
       
    }
}
Posted
Updated 29-Apr-14 18:56pm
v3

you can have a look at this JQuery AJAX with ASP.NET MVC[^]
 
Share this answer
 
Yes dear... You are done almost perfect. But there are minor mistake at the time of response rendering on html page.

Just use $("tbody","#tbDetails") insted of $("#tbDetails"), Because you trying to fill rows inside tbody tag of HTML table. Also there are another options for append() method like html(), innerText, outerText,appendChild,innerHTML,....
 
Share this answer
 
v2
Comments
nira.parmar 28-Mar-14 6:04am    
But it doesn't go into for loop
Mahesh Pandekar 28-Mar-14 6:17am    
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("tbody","#tbDetails").append("<tr><td>" + data.d[i].userName + "</td><td>" + data.d[i].userRole + "</td></tr>");
}
},
Hi,
There are certain changes required in your code specially from controller
1) You are making a GET request to your control
2) You are expecting a JSON datatype return from your controller

So change your controller to something like below.
public JsonResult JsonGet()
        {
            
            List<string> user = new List<string>() { "Harish" , "Verma"};
           
            var y = new { data = user };
            return Json(y, JsonRequestBehavior.AllowGet);
        }</string></string>


Now is your script code you can use JSON.stringify() method to see how your json looklike and can fill your tbody accordingly. For the above example json string will be like
C#
{"data":["Harish", "Verma"]}


you can use $.each() loop on the json object in your sucess method. Hope it will solve your issue
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900