Saravanan
Saravanan

Reputation: 7844

using json to object binding in asp.net mvc2

I am trying to bind a JSON stringified object to a model and few other strings in the controller and it is not working.

is it not possible,

$.ajax({
url: "/SrcManager/AddDataSource",
type: "POST",
data: JSON.stringify({
    content: ct,
    dataSourceName: $("#dataSrcName").val(),
    parameters: parametersCollection,
    sourceContentId: sourceContentId,
    sourceId: null,
    type: contType
}),
success: function (data) {
    if (data.length > 1)
    {
        alert("DataSource Saved Successfully");
        $("#dataSrcId").val(data);
    }
}
});

and var parametersCollection = [];

function IPParameters(paramName, paramValue) { this.ParamName = paramName; this.ParamValue = paramValue; }

*** action method : public string AddDataSource(ContentModel scvm){.........}

Why does the above not work. Is this not supported or any mistake in the code, kindly suggest the right way.

In the ContentModel, i map the parameters to List<Parameters>.

I have added the JsonValueProviderFactory also in global.asax.

The C# model is :

public class SourceContentViewModel
{
    public string sourceId { get; set; }

    public string dataSourceName { get; set; }

    public string sourceContentId { get; set; }

    public string content { get; set; }

    public string type { get; set; }
    public List<Parameters> parameters { get; set; }

    public SourceContentViewModel()
    {
        parameters = new List<Parameters>();
    }
}

public class Parameters
{
    public string ParamName { get; set; }
    public string ParamValue { get; set; }
}

Upvotes: 0

Views: 850

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You can't send JSON to an ASP.NET MVC 2 application as there is no JSON provider factory out-of-the-box that will allow you to read the request. It is built in ASP.NET MVC 3. You may take a look at the following blog post and include the JsonValueProviderFactory discussed there. Then you will be able to send JSON requests to your ASP.NET MVC 2 controller actions after registering it:

protected void Application_Start() 
{
    RegisterRoutes(RouteTable.Routes);
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

Also notice the contentType: 'application/json; charset=utf-8' setting when sending the request which instructs the binder that you are sending a JSON request.

Upvotes: 2

Related Questions