我的
iphone客户端发布以下json到我的mvc服务.
当从html表单发布数据时,它将自动将表单数据转换为usermodel,并将对象传递给我的Create方法,但是当我将来自iphone的请求正文中的 JSON字符串发送回为null时.
当从html表单发布数据时,它将自动将表单数据转换为usermodel,并将对象传递给我的Create方法,但是当我将来自iphone的请求正文中的 JSON字符串发送回为null时.
从JSON到Object的转换将是最干净的解决方案.
我不是为不同的客户端创建多个方法,所以我试图得到相同的方法来工作在iphone和mvc客户端.
我的要求的身体:
{
"firstName" : "Some Name","lastName" : "Some Last Name","age" : "age"
}
我的模型和行动结果
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);
}
解决方法
你需要设置HTTP头,接受’application / json’,以便MVC知道你是传递JSON,并进行解释.
accept: application/json
查看更多信息:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
更新:使用MVC3和jQuery的工作示例代码
控制器代码
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; }
}
}
查看代码
@{ 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: { "firstName": "Some Name","lastName": "Some Last Name","age": "30" },accept: 'application/json'
});
};
$(document).ready(function () {
sample.postData();
});
</script>
<h2>Index</h2>