Zachary Scott
Zachary Scott

Reputation: 21188

ASP.NET MVC2 and JSON model binding with validation to an action method

Phil Haack's blog entry describes this process using ASP.NET MVC 2's futures and Crockford's json2.js. John Resig also recommends using Crockford's json2.js in this article regarding "use strict";.

To get this feature today, would you still download the MVC 2 Futures, or is this included in the MVC 2 final, or is this part of the new MVC 3 preview?

Edit:

As Per Jakub's suggestion (and Phil Haack, woot!), my script finally works. A big appreciation to both of them.

<script type="text/javascript">
$(document).ready(function () {

    var myData = {};
    myData.value = '9/14/2010 12:00:00 AM';
    var myJson = JSON.stringify(myData);

    $.ajax({
        type: "POST",
        url: "/AdSketch/GetPrintProducts",
        data: myJson, 
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            alert(result);
        }
    });
});
</script>

The MVC controller code:

public JsonResult GetPrintProducts(string value)
{   // At this point "value" holds "9/14/2010 12:00:00 AM"
    return Json(value);
}

Upvotes: 4

Views: 946

Answers (2)

Dariusz Tarczynski
Dariusz Tarczynski

Reputation: 16731

In MVC 3 there is ValueProviderFactories provided out of the box.

Upvotes: 2

Jakub Konecki
Jakub Konecki

Reputation: 46008

For MVC2 you need Futures. Get the dll, add reference to it and in Global.asax add (Application_Start):

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

Don't know about MVC3 - I'm waiting for an RTM. But I do encourage you to give it a go, as sending JSON up to Actions is a pure bliss ;-)

Upvotes: 3

Related Questions