Modelbinding with complex objects in ASP.NET MVC

 

image_thumb738-552x194

Basics: The modelbinding in ASP.NET is “relatively” clever and you are able to bond almost everything. All you have to do is to understand how the binding works and you often found that out if you take a look via Fiddler and co. at what is transmitted as HTTP.

Object model

public class Foobar
{
    public string Buzz { get; set; }

    public int Foo { get; set; }

    public List<Foobar> Children { get; set; }
}

The model is very simple but it contains objects from the same type as a list.

Action method

We want to transmit those files to the computer (who doesn’t interact with them at all but it’s enough for the example):

public ActionResult Test(string name, List<Foobar> foobars)
{
	return View("Index");
}

I present you three different models of how to integrate complex objects into this method.

Model 1: easy form (Postback – no AJAX)

@using (Html.BeginForm(“Test”, “Home”, FormMethod.Post))

{

    <input type=”text” name=”Name” value=”Testvalue” />

    <input type=”text” name=”Foobars[0].Buzz” value=”Testvalue” />

    <input type=”text” name=”Foobars[0].Foo” value=”123123″ />

    <input type=”text” name=”Foobars[1].Buzz” value=”Testvalue” />

    <input type=”text” name=”Foobars[1].Foo” value=”123123″ />

    <input type=”text” name=”Foobars[2].Buzz” value=”Testvalue” />

    <input type=”text” name=”Foobars[2].Foo” value=”123123″ />

    <input type=”text” name=”Foobars[3].Buzz” value=”Testvalue” />

    <input type=”text” name=”Foobars[3].Foo” value=”123123″ />

    <input type=”text” name=”Foobars[3].Children[0].Buzz” value=”KIND!” />

    <input type=”text” name=”Foobars[3].Children[0].Foo” value=”123123″ />

    <button>Ok</button>

}

With the “[NUMBER]” of the field the MVC Binder will know that this is only a list. It’s possible to get this as interlaced as you like. It’s important at that point that the numbering is continuous.

image

If you take a look on what is transmitted you will recognize that it isn’t that complicated at all:

image

Model 2: send the form via jQuery with Ajax

That’s what the example looks like:

$("#FormButton").click(function () {
    $.ajax({
        url: "@Url.Action("Test", "Home")",
        type: "POST",
        data: $("form").serializeArray()
    });

});

I grab the Click-Event of one button and get all the information’s via “serializeArray()”. We are going to take another look at the transmission. It’s important that there are only form files as Content-Type not JSON:

image

Model 3: Files created with Javascript – transmit Javascript Arrays with AJAX

Model 1 and 2 rely on the existence of a form. If you prefer to build your files in Javascript only and if you don’t want to build a “Hidden”-Form you might prefer this model.

$("#ScriptButton").click(function () {

    var foobars = new Array();

    for (i = 0; i < 10; i++) {
        foobars.push({ Buzz: "Test!", Foo: 12123, Children: { Buzz: "Child!", Foo: 123213} });
    }

    var requestData = { };
    requestData.Name = "Testadalsdk";
    requestData.Foobars = foobars;

    $.ajax({
        url: "@Url.Action("Test", "Home")",
        type: "POST",
        contentType: 'application/json;',
        dataType: 'json',
        data: JSON.stringify(requestData)
    });

});

First we create an Array in Javascript:

image

Next we create a “requestData” and set our “Name”-Testproperty and connect the Array.

To transmit this to our controller we need to transform the files. The easiest way for this is the JSON-format. Newer browsers have a JSON support but to be sure I recommend you to use the JSON Helper from Douglas Crockford “json2.js” (it’s also available on NuGet).

With this script you will receive the method “JSON.stringify()” (the link leeds to the Mozialle Developer Center – the same thing is in the MSDN) which transforms an object into JSON.

Therefore we set the following properties in the AJAX request so our controller will be able to understand what he receives:

contentType: ‘application/json;’,

dataType: ‘json’,

That’s what is going to be transmitted:

image

Because of the content-type: application/json the MVC framework uses the JSON modelbinder automatically and the information’s will be transmitted to the controller.

Result

You are able to do almost everything with the MVC Modelbinding if you keep in mind some basic rules. Also a look onto what is transmitted via HTTP will help you a lot with the Debugging.

The whole demo application is available here – but there is also code included from another Blogpost.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by

Learn more about our team.

3 Responses

  1. Excellent website, congratulations for what you’re doing here.

    Reply
  2. I like your website .
    your article is well formed and written simple and practical.
    Good Luck!

    Reply
  3. Thanks for this one it helped me out trying to do some rather silly binding from a knockout view model.

    Reply

Comment on this post

Recent Posts

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    How to access an Azure Website with the local IIS Manager

    Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information there are more details visible at the IIS Manager. For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also possible to […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

Support us