POST JSON with MVC 4 API Controller

后端 未结 5 1772
刺人心
刺人心 2020-12-09 10:01

I have this code:

   $.ajax({


        type: \"POST\",
        url: \"/api/slide\",
        cache: false,
        contentType: \"application/json; charset=u         


        
5条回答
  •  心在旅途
    2020-12-09 10:35

    Define a view model:

    public class SlideViewModel
    {
        public string Title { get; set; }
    }
    

    then have your controller action take this view model as argument:

    public class SlideController : ApiController
    {
        // POST /api/Slide
        public void Post(SlideViewModel model)
        {
            ...
        }
    }
    

    finally invoke the action:

    $.ajax({
        type: 'POST',
        url: '/api/slide',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ title: "fghfdhgfdgfd" }),
        success: function() {
            ...    
        }
    });
    

    The reason for that is that simple types such as strings are bound from the URI. I also invite you to read the following article about model binding in the Web API.

提交回复
热议问题