1

I am trying to post data in JSON format to a .NET MVC Controller like this.

$.ajax({
         type: 'POST',
         url: 'http://mvc.tester.local/Home/NameConverter',
         data: JSON.stringify({ convertermodel.InputName: obj.currentTarget.value }),
         contentType: 'application/json'
});

But Javascript complains about the JSON.Stringify() bit.
The convertermodel.InputName to be exact.

The thing is I actually need this JSON data name to be that way i.e. have the same name as a property in my model; in order to take advantage of reflection for automatic binding.

This is my model:

public class NamesViewModel
{
    public NameConverterModel convertermodel = new NameConverterModel();        
}

and the sub Class

public class NameConverterModel
{
    private string _inputName = "";
    public string InputName
    {
        get { return _inputName; }
        set { _inputName = value; }
    }    
}

How can I solve this please ?

I hope I am clear enough.

1 Answer 1

1

You would need your JSON to be of the structure like this:

{"convertermodel" : {
                      "InputName" : obj.currentTarget.value
                    }
}

Your JSON representation of your object needs to reflect the appropriate nesting that your object model that you're trying to model in the client-side requires. So defining your JSON by nesting your hierarchy at one level won't work -- you need to create objects of objects like you did in your C# code.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, why didn't I think of that ? I haven't tested this, but I'm sure it is the right answer. Testing now, thanks
I hope this helps. If it does, don't forget to mark this as an answer. It will help your accept percentage.
No problem - glad to be of help!

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.