Here's an example. It assumes that you are using ASP.NET MVC 3.0 which has a built-in JsonValueProviderFactory
. If this is not your case you could take a look at this blog post.
View model:
public class MyViewModel
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomeAction(MyViewModel model)
{
return Content("success", "text/plain");
}
}
View:
<script type="text/javascript">
var http = new XMLHttpRequest();
var value = '{ "prop1": "value 1", "prop2": "value 2" }';
// It would be better to use JSON.stringify to properly generate
// a JSON string
/**
var value = JSON.stringify({
prop1: 'value 1',
prop2: 'value 2'
});
**/
http.open('POST', '/Home/SomeAction', true);
http.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
http.setRequestHeader('Content-Length', value.length);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(value);
</script>