Question

I have the following View model

public class SaveFileRequestViewModel
{
    public string FileName { get; set; }
    public ISearchAccounts AccountSearch { get; set; }
}

ISearchAccounts is defined like this

public interface ISearchAccounts
{
    int Id { get; set; }
    SearchTypes SearchType { get; }
    string UserId { get; set; }
    DateTime CreatedOn { get; set; }
    string Description { get; set; }
    AccountNumberType AccountNumberType { get; set; }
}

What I'd like to do is use a model binder to catch the SaveFileRequestViewModel check the SearchType property (that came in the JSON) and use JSON.NET to serialize to the appropriate implementation of ISearchAccounts. Addtional properties are in the JSON and JSON.NET will know what to do. My Problem is when I try and Bind the AccountSearch property of the SaveFileRequestViewModel property it is null.

bindingContext.ValueProvider.GetValue("AccountSearch");

I can access properties when I scope them specifically like

bindingContext.ValueProvider.GetValue("AccountSearch.SearchType");

I'm open to other approaches, but I'm thinking I just want to grab the portion of the submitted JSON that is encompassed by AccountSearch.

Here is an example of my submitted JSON. It could be significantly more complex depending on what options the user selects in the UI

{
"FileName":"filename 2014-03-03 16.24.17",
"AccountSearch":
    {
        "AccountNumberType":"XXX",
        "AccountNumbers":"123456789 6789101245",
        "SearchType":"Multiple"
    }
}

No correct solution

OTHER TIPS

Have a look at this recent answer: https://stackoverflow.com/a/22082643/148998

To summarize there is a default JsonValueProviderFactory for the Asp.net-mvc 3 framework, as long as your JSON data posted to the Action matches the Model it should bind the data correctly.

Be careful of getting the names of properties wrong, it wont find and bind it.

I suggest to serialize a populated version of your model to JSON and have a look at how it is structured, as long as you send it back in the same structure it should be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top