views:

75

answers:

1

In my web app I have a dynamically generated form that I use to create a JSON object to pitch back to an Action. As seen here:

    function getConfigItemWithValidators() {
        log.info("getConfigItemWithValidators()");
        var oConfigItem = { 
            "Name": $("#txtName").html(),
            "InputFileCellIndex": $("#inpFieldIndex").val(), 
            "Validators": new Array() };

        for (var i = 0; true; i++) {
            var oHiddenValidatorName = $("[name=hidVld"+i+"]");
            var oHiddenValidatorVal  = $("[name=txtVld"+i+"]");
            if ($("[name=hidVld" + i + "]").length > 0) {
                var oValidator = {
                    "ValidationType": oHiddenValidatorName.val(), 
                    "ValidationValue": oHiddenValidatorVal.val() };
                oConfigItem.Validators.push(oValidator);
            }
            else
                break;
        }
        return oConfigItem
    }

    function saveConfigItemChanges() {
        log.info("saveConfigItemChanges()");
        var oConfigItem = getConfigItemWithValidators();
        $("#divRulesContainer").hide("normal");
        $.getJSON("PutValidationRules", oConfigItem, 
                   saveConfigItemChangesCallback);
    }

In my action, while debugging, I notice that model.Validators is empty:

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult PutValidationRules(ConfigItem model)
    {
        // model.Validators is empty
        return Json(true);
    }

Here is the code to ConfigItem:

public class ConfigItem
{
    public string Name { get; set; }
    public int InputFileCellIndex { get; set; }

    private IList<Validator> _validators = new List<Validator>();
    public IList<Validator> Validators
    {
        get
        {
            return _validators;
        }
    }

    public void AddValidator(Validator aValidator)
    {
        aValidator.ConfigItem = this;
        _validators.Add(aValidator);
    }
}

Is there something I need to do to get ConfigItem.Validators to get built for my JSON requests?

+1  A: 

It is empty because default binder does not work for arrays very well. You will need to implement a custombinder. You can see here an example of custombinders

Jenea
Instead of writing a custom binder, I made my form accommodate the built-in binder.
JMP
Of course it is always a choice but names of the attributes can be changed and then you have to make similar changes in Views and maybe even in HTML slicing.It adds in my opinion unnecessary amount of work.
Jenea