简体   繁体   中英

mvc: displaying json data in mvc view from controller

Hi guys I am facing a problem in displaying json data from controller to view.
json data is displayed in the browser. It is not using master page and
my view is not a partial view. I don't understand what the problem is

my controller is as follows

public JsonResult Grid()
{
    var data = en.customers.Select(x => new ProductModel()
    {
        fname = x.fname,
        lname = x.lname,
        username = x.username,
        password = x.password

    }).ToList();

    return Json(data, JsonRequestBehavior.AllowGet);
}

my view is as follows

<script type="text/javascript">

    $(document).ready(function () {

        $.getJSON("/Home/Grid", null, function (data) {
            var items = '<table><tr><th>FNAME</th><th>LNAME</th> <th>USERNAME</th><th>PASSWORD</th></tr>';
            $.each(data, function (i, cus) {
                items += "<tr><td>" + cus.fname + "</td><td>" + cus.lname +  "</td><td>" + cus.username + "</td><td>" + cus.password + "</td></tr>";
            });
               items += "</table>";

            $('#mytbl').html(items);
        });

    });

<script type="text/javascript">
$(document).ready(function () {
    $.ajax({
        url : "/Home/Grid",// url
        type : "GET", // GET or POST
        data : {}, // null data
        dataType : "json",// expected type in return
        success : function(data){
            var table = '<table><tr><th>FNAME</th><th>LNAME</th> <th>USERNAME</th><th>PASSWORD</th></tr>';
            for(var i=0; i<data.length; i++){
                table += "<tr><td>" + data[i].fname + "</td><td>" + data[i].lname +  "</td><td>" + data[i].username + "</td><td>" + data[i].password + "</td></tr>";
            }
            table += "</table>";
            $('#mytbl').html(table); 
        },
        error : function(data){
            alert("Internal Server Error:\n"+data);
        },
    });
});
</script>

Try this...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM