title: MVC Web Api Get Data with Ajax
body: <p>I'm trying to get all my posts from the database to be displayed with the help of ajax or getjson but can't get it to work. Using mvc web api and I have a view where I want to display it.  There is a method working called post so nothing wrong with my routing etc.</p>
  
  <p>Code for my views js-script, I want to display all posts with the help of my mvc api controller and ajax in a div called #userMessage.</p>
  
  <pre><code>    $(document).ready(function() {
  
      $('#btnGetPosts').click(function() {
          jQuery.support.cors = true;
          var recieverID = $('#RecieverID').val();
  
          $.ajax({
              url: "/api/Posts/GetPosts" ,
              //data: (?)
              type: "GET",
              dataType: "jsonp",
              error: function(request, status, error) {
                  alert(request.responseText);
              },
              success: function(data) {
                  alert(data);
              }
          });
      });
  });
  </code></pre>
  
  <p>my controller method to get all the posts</p>
  
  <pre><code>     //   GET: api/Posts
          public IEnumerable&lt;Post&gt; GetPosts()
          {
  
   //querystring is made to get the recieverID, it's also reachable in the view.      //("#RecieverID")
              string querystring = HttpContext.Current.Request.QueryString["Username"];
  
  
  
              // Converts Username querystring to a user-id
              int id = UserRepository.GetUserId(querystring);
  
              // uses linq to get a specific user post (all posts)
              var userPost = PostRepository.GetSpecificUserPosts(id);
  
              return userPost;
          }
  </code></pre>
  
  <p>my PostRepository.GetSpecifiedUserPosts method in my repository</p>
  
  <pre><code>  public List&lt;Post&gt; GetSpecificUserPosts(int user)
      {
          using (var context = new DejtingEntities())
          {
              var result = context.Posts
                  .Where(x =&gt; x.RecieverID == user)
                  .OrderByDescending(x =&gt; x.Date)
  
  
                  .ToList();
  
              return result;
          }
  </code></pre>