0

I have a question regarding a Form Post of an complex Model. My Model has a subclass and IEnumerables:

public class MyViewModel
{
    public int SingleInteger { get; set; }
    public IEnumerable<int> MultipleInts { get; set; }
    public IEnumerable<MySubclass> AssembledClass { get; set; }
    public IEnumerable<string> MultipleStrings { get; set; }
}

public class MySubclass
{
    public int Quantity { get; set; }
    public int Type{ get; set; }
}

What is the best way to get the Input from my View to my Controller? Can the Modelbinder even bind this?

2
  • There is no such thing as MVC6 ;) Commented Dec 20, 2017 at 10:06
  • If this is a real form post, the actual data design of your HTML form is a lot more interesting than this. – But yeah, the model binder won’t be a problem here. Commented Dec 20, 2017 at 11:08

1 Answer 1

0

Can the Modelbinder even bind this?

Yes, and it can do a lot more complexed stuff then this class structure.

What is the best way to get the Input from my View to my Controller?

Post is as json.

Example:

You could POST this json

{"singleInteger":1,"multipleInts":[1,2,3],"assembledClass":[{"quantity":1,"type":2}],"multipleStrings":["one","two"]}

To an controller method like this

public IActionResult Post([FromBody]MyViewModel model)

And it will be translated into an instance of MyViewModel like this

var model = new MyViewModel
{
    SingleInteger = 1,
    MultipleInts = new List<int>(){ 1,2,3 },
    AssembledClass = new List<MySubclass>{
        new MySubclass 
        {
            Quantity = 1,
            Type = 2
        }
    },
    MultipleStrings = new List<string>(){ "one", "two"} 
};
Sign up to request clarification or add additional context in comments.

Comments

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.