2013-02-11 51 views
0

我試圖在文本框中鍵入國家/地區名稱並單擊按鈕時獲取客戶(姓名和地址)列表。使用getJSON在MVC中顯示客戶名稱(姓名,地址)

這裏是視圖:

<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); 
} 

我的問題是:

我)當我使用以下

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); 
} 

它工作正常,當我使用「字符串ID」但是當我使用「字符串國家」,然後「其中r.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); 

讚賞任何幫助的方式。

+0

嘗試input'這裏'$ .getJSON(URL,{數據:國家},功能(數據) {@ – Jai 2013-02-11 10:24:29

+0

i)@Jai沒有任何反應。 – 2013-02-11 10:48:58

回答

1

試試這個

$('#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'); 
}); 

這裏是放置`data`了,而不是`的文檔http://api.jquery.com/jQuery.getJSON/

相關問題