How do you post a JSON file to an ASP.NET MVC Action?

前端 未结 5 1604
予麋鹿
予麋鹿 2020-12-01 18:51

My iphone client posts the following json to my mvc service. When posting data from html form it automatically converts form data to UserModel and passes the object to my Cr

5条回答
  •  [愿得一人]
    2020-12-01 19:13

    You need to set the HTTP Header, accept, to 'application/json' so that MVC know that you as passing JSON and does the work to interpret it.

    accept: application/json
    

    see more info here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

    UPDATE: Working sample code using MVC3 and jQuery

    Controller Code

    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public JsonResult PostUser(UserModel data)
            {
                // test here!
                Debug.Assert(data != null);
                return Json(data);
            }
        }
    
        public class UserModel
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int Age { get; set; }
        }
    }
    

    View Code

    @{ ViewBag.Title = "Index"; }
    
    
    
    

    Index

提交回复
热议问题