使用getJSON在MVC中显示客户列表(名称、地址)

本文关键字:名称 地址 列表 客户 getJSON MVC 显示 使用 | 更新日期: 2023-09-27 17:58:34

当在文本框中键入国家/地区名称并单击按钮时,我正在尝试获取客户列表(名称和地址)。

以下是视图:

<p>
    Enter country name @Html.TextBox("Country")
    <input type="submit" id="GetCustomers" value="Submit"/>
</p>

这是JSON调用:

<script type="text/jscript">
    $('#GetCustomers').click(function () {
        //var url = "/Home/CustomerList";
        //var Country = $('#Country').val();
        //$.getJSON(url, { input: Country }, function (data) {
        $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {
            var items = '<table><tr><th>Name</th><th>Address</th></tr>';
            $.each(data, function (i, country) {
                items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
            });
            items += "</table>";
            $('#rData').html(items);
        });
    })
</script>

这是控制器:

public JsonResult CustomerList(string Id)
{
    var result = from r in db.Customers
                    where r.Country == Id
                    select r;
    return Json(result);
}

我的问题是:

i)当我使用以下

var url = "/Home/CustomerList";
var Country = $('#Country').val();
$.getJSON(url, { input: Country }, function (data) {

它并没有将prameter传递给CustomerList方法,但是下面的工作得很好

$.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {

ii)当我使用以下JSON时

$.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {

然后按照CustomerList方法

public JsonResult CustomerList(string Id)
{
    var result = from r in db.Customers
                    where r.Country == Id
                    select r;
    return Json(result);
}

当我使用"string Id"时,它可以正常工作,但当我先使用"string country",然后使用"where r.country==country"时,就不起作用了。

iii)这是处理响应的正确方法吗,不起作用

var items = '<table><tr><th>Name</th><th>Address</th></tr>';
$.each(data, function (i, country) {
    items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);

感谢您的帮助。

使用getJSON在MVC中显示客户列表(名称、地址)

试试这个

 $('#GetCustomers').click(function () {
    //var url = "/Home/CustomerList";
    //var Country = $('#Country').val();
    //$.getJSON(url, { input: Country }, function (data) {
    $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {
        var items = '<table><tr><th>Name</th><th>Address</th></tr>';
        $.each(data, function (i, country) {
            items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
        });
        items += "</table>";
        $('#rData').html(items);
    },'json');
});

这是文件http://api.jquery.com/jQuery.getJSON/