2

Can anyone lead me to examples showing how to convert incoming JSON to a Model in MVC3?

0

2 Answers 2

3

That's already handled for you by the framework.

So you define models:

public class MyViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Complex Complex { get; set; }
    public IEnumerable<Foo> Foos { get; set; }
}

public class Complex
{
    public int Id { get; set; }
}

public class Foo
{
    public string Bar { get; set; }
}

then a controller action taking this model:

[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
    ...
}

and finally you hammer this controller action with a JSON request matching the structure of your view model:

$.ajax({
    url: '@Url.Action("SomeAction")',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        id: 1,
        name: 'john smith of course, why asking?',
        complex: {
            id: 3
        },
        foos: [
            { bar: 'the bar' },
            { bar: 'the baz' },
        ]
    }),
    success: function(result) {
        alert('hooray');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

We decided to make the webservice SOAP. No need for JSON.
0

http://james.newtonking.com/projects/json-net.aspx

I would add more, but the example code is also on that front page.

6 Comments

I don't want to convert my model TO JSON, I want to convert JSON to my model. I don't see that package doing that.
You can DEserialize the JSON, then map the data to your model
Why would you do all that when the framework already handles this for you?
@DarinDimitrov the OP stated "incoming JSON" In my experience, json.NET has handeled this much easier than the DataContractJsonSerializer or JavaScriptSerializer. Here is a really good writeup of someone consuming Stack Overflow's JSON API freshbrewedcode.com/jonathancreamer/2012/02/07/…
Who said anything about DataContractJsonSerializer? ASP.NET MVC doesn't use that. It uses a JsonValueProviderFactory factory based on the JavaScriptSerializer class. And everything's already built-in. The link you provided illustrates the client/consuming part, not the server side JSON to view model conversion part which is what I thought the OP was asking about.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.