Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

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

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 Create method, but when I send the JSON string in the body of my request from iphone it comes back as null.

What would be the cleanest solution to do the conversion from JSON to Object.

I rather not create multiple methods for different clients, so I'm trying to get the same method to work on iphone, and mvc client.

Body of my request:

{
   "firstName" : "Some Name",
   "lastName" : "Some Last Name",
   "age" : "age"
}

My Model and Action Result

public class UserModel
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
}

[HttpPost]
public Create ActionResult(UserModel user)
{
   // user is null
   userStorage.create(user);
   return SuccessResultForModel(user);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"; }
<script src="../../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    var sample = {};
    sample.postData = function () {
        $.ajax({
            type: "POST", url: "@Url.Action("PostUser")",
            success: function (data) { alert('data: ' + data); },
            data: JSON.stringify({ "firstName": "Some Name", "lastName": "Some Last Name", "age": "30" }),
            accept: 'application/json'
        });
    };
    $(document).ready(function () {
        sample.postData();
    });
</script>

<h2>Index</h2>

** Update ** I added JSON.stringify to the JS object before I pass it to the data element in the AJAX Request. This just makes the payload more readable, however the Controller will interpret both formats of the data similarly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...