在Web Api 7 Mvc4中选择一项



我是webapi的新手我试图在mvc4项目中使用web API和jquery列出项目。(我使用虚拟数据)

我在控制器和jquery中使用了以下代码
public class DummyController : ApiController
{
    Inbox[] inb = new Inbox[]
    {
        new Inbox{Id = 1,Auther="Vivek",File="CT107837607.pdf"},
        new Inbox{Id = 2,Auther="Ajay",File="CT10783553607.pdf"},
        new Inbox{Id = 3,Auther="Anu",File="ST107537607.pdf"}
    };
    public IEnumerable<Inbox> GetAllEmails()
    {
        return inb;
    }
 }
 $(document).ready(function () {
//Get All from controller and list in the  page    
 $.ajax({
    type: "GET",
    url: "api/Dummy/GetAllEmails",
    contentType: "json",
    dataType: "json",
    success: function (data) {
        $.each(data, function (key, value) {              
            var jsonData = JSON.stringify(value);               
            var objData = $.parseJSON(jsonData);
            var id = objData.Id;                
            var auther = objData.Auther;         
            var file = objData.File;                
            var div = '<a href="#"><div class="ibx-itm">' +                         
                        '<div class="ibx-auth">' + auther + '</div>' +
                        '<div class="ibx-file alt"> ' + file + ' uploaded</div>' +
                        '</div>' +
                        '</a>';
            $(div).appendTo('#ibx-li-dt');
        });            
    },
    Error: function (XHR) {
        alert(XHR.responseText);
        }
     });   
  });

这段代码列出了所有的项目…然后我想在点击一个特定的项目时按id获取一个项目

为此,我编写了以下控制器代码。则列表不工作

      public Inbox GetEmail(int id)
      {
        var inboxit = inb.FirstOrDefault((I) => I.Id == id);
        if (inboxit == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return inboxit;
      }

我也必须知道我如何传递id到下面的jquery时调用这个函数

function GetStudentById()
{
  $.ajax({
    type: "GET",
    url: "api/Dummy/GetEmail",
    contentType: "json",
    dataType: "json",
    success: function (data) {          
    var jsonData = JSON.stringify(data);       
    var objData = $.parseJSON(jsonData);
    var objData = $.parseJSON(jsonData);
    .....
},
Error: function (XHR) {
                  alert(XHR.responseText);
   }
 });

}

尝试:

url: "api/Dummy/GetEmail/7" (7 is your id)

最新更新