I have a method (no '[HttpPost]' => GET?)

public class HomeController : Controller { public async Task<ActionResult> UserFriendsPartial(int userId, int count) { var friends = await RelationshipService.GetFriendsByUserId(userId, count); return PartialView(friends); } } 

Have a presentation

 <div id="UserFriends"> @Html.Action("UserFriendsPartial", "Home", new { userId = Model.Id, count = 6 }) </div> <button id="AddToFriends"/> <script type="text/javascript"> $('#AddToFriends').click(function () { FriendsRefresh(6); }); function FriendsRefresh (pCount) { var p = { userId: @Model.Id, count: pCount }; $.ajax({ url: '@Url.Action("UserFriendsPartial", "Home")', type: 'POST', contentType: "application/json;charset=utf-8", data: JSON.stringify(p), success: function (data) { $('#UserFriends').html(data); } }); } </script> 

When the page is loaded, the method is called via Html.Action (if you add the HttpPost tag in the controller to the method, it will not work). And when you press the button, the same method is called an AJAX POST request. The question is why does this work?

  • can here userId: @ Model.Id quotes need userId: '@ Model.Id' - akrasnov87
  • @ akrasnov87 the fact is that everything works fine, I just can’t understand how the controller method without the HttpPost tag can be called by an AJAX POST request and how (GET or POST) it is called Html.Action - dizar47

1 answer 1

You have a method that handles both types of GET and POST requests. When you call the controller method via Html.Action, the essence of the request (its global headers) does not change. He was like you (probably) GET and remains the same. That is, when the method is called, the global request is the same, and for the Html.Action call, a new Request (Request) is not generated.

When you add the [HttpPost] attribute to a method, you limit the http-request methods handled by the controller method to only one - POST . Therefore, when you call Html.Action for a global GET this no longer works, but for a POST request via Ajax works.