Home » Tutorials » Update Form Fields with JSON result in ASP.NET MVC

Update Form Fields with JSON result in ASP.NET MVC

Wouldn’t it be nifty to receive a JSON result object from AJAX and it automagically updates your form fields? Those who said “No” leave now!
I had to find a way to iterate through my JSON properties and, if I named the fields the same as the JSON properties, update them all in one go.

Lets use a simple “Person” model and have a look at the ASP.NET MVC action:

public ActionResult GetPerson(int id)
{
    var person = Context.GetPerson(id);
    return Json(new
                    {
                        success = true,
                        model = new
                                    {
                                        person.Id,
                                        person.Name,
                                        person.Surname,
                                        person.Age,

                                    }
                    });
}

As you can see this returns a DTO (data transfer object) as JSON result and is ready to be consumed via AJAX…

$.getJSON("/Person/1", function(data) {
    if (data.success) {
        $.updateForm(data.model);
    } else {
        alert("An error occurred");
    }
});

All we then need is the magical “$.updateForm” method that contains all the voodoo:

jQuery.updateForm = function(model) {
   // we iterate through all the properties
   for (var property in model) {
        // evaluate the expression to get the value
        var propertyValue = eval("model." + property);
        // and update the field
        $("#" + property).val(propertyValue);
    }
};

Currenty this will work fine for textboxes and textareas as this was all the functionality I needed for now. If anyone extends this for “select”, “checkbox”, “radiobutton” etc… please share with us so I can update this post.

3 Comments

  1. [...] to VoteUpdate Form Fields with JSON result in ASP.NET MVC (10/4/2009)Sunday, October 04, 2009 from MarcelWouldn’t it be nifty to receive a JSON result object from AJAX [...]

  2. Update Form Fields with JSON result in ASP.NET MVC – Marc Dormey…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  3. 9eFish says:

    Update Form Fields with JSON result in ASP.NET MVC | Marc Dormey…

    9efish.感谢你的文章 – Trackback from 9eFish…

Leave a Reply

Copyright © 2009 · Marc Dormey · All Rights Reserved · Posts · Comments
Designed by Theme Junkie · Powered by WordPress