动态形式建筑与knockoutjs

时间:2012-10-30 12:15:38

标签: ajax asp.net-mvc-3 knockout.js json.net form-post

我需要从数据库构建动态表单。我有跟随实体来动态定义表单字段:

    public class FormField {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }    // Possible values are: 'Radio','Combo','Text'. A dropdown will be created for a Combo type of element, a radio set for Radio type of element and a text input for Text type of element.
        public string Options { get; set; } // Only relevant in case of Radio/Combo type
        public string Default { get; set; } // Default value in case of Type 'Text' and selected value in case of Type 'Radio/Combo'
        public string Blankout { get; set; }// An expression to define when this field should be hidden 
    }

    /* A sample JSON array (from the DB) to build the form would be:
       [
        { Name:"Gender", Type:"radio", Options:["Male","Female","Unknown"], Default:"Male", Blankout:"Never" },
        { Name:"Age", Type:"text", Options:"None", Default:15, Blankout:"Never" },
        { Name:"Neighbourhood", Type:"Combo", Options:["Eastern","Western","Northern","Southern","Central"], Default:"Central", Blankout:"if (Age < 40 or Voted='Obama')" },
        { Name:"Voted", Type:"Combo", Options:["Obama","Romney","Harry Potter"], Default:"Harry Potter", Blankout:"if ((Gender='Female' and Age < 15) or Neighbourhood='Eastern'" }
       ]
    */

我可以从DB中的'FormField'记录构建一个动态表单,但问题是我需要跟踪任何表单字段值的变化,当值发生变化时我需要发送所有表单数据服务器(异步)以评估服务器上的“空白”公式。如果我做这个改变跟踪的东西没有KnockoutJS它没有响应,变得非常复杂。 我已经阅读了几个KnockoutJS的教程,但是无法弄清楚如何为这个特定问题组织我的ViewModel。

任何帮助都将不胜感激。

更新1

我尝试使用以下代码将此表单数据发布到控制器:

    $.ajax({
            type: "POST",
            url: "/MyController/GetBlankoutElements",
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(ko.toJSON(self)),
            success: function(result) {
                alert(result);
                //self.HiddenElements(result.split(','));
            }
    });

在我的控制器中,我尝试了以下代码:

    [HttpPost]
    public ActionResult GetBlankoutElements(List<MyFieldViewModel> Fields)
    {
        return Json(Fields); // List, Fields is null here
    }

Her是MyFieldViewModel类的样子:

    public class MyFieldViewModel 
    {
        public string Title { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Default { get; set; }
        public string[] Options { get; set; }
    }

我尝试了Post an Array of Objects via JSON to ASP.Net MVC3

中描述的提示

以下是我执行 alert(ko.toJSON(self))时打印出来的Json数据

    {"Fields":
        [{"Title":"CCType","Name":"CCType","Type":"Radio","Default":"Enterprise","Options":["Enterprise","Express","CVP","PCCE"]},{"Title":"Industry","Name":"Industry","Type":"Combo","Default":"Banks","Options":["Banks","ServiceProvider","Outsourcer","Airlines","Utilities","Government","Retail"]},{"Title":"Customer Lab","Name":"CustomerLab","Type":"Combo","Default":"0","Options":["0","1"]},{"Title":"No of Agents","Name":"Agents","Type":"Text","Default":"if(c.CCType==\"CVP\") then 10 else 25","Options":[]},{"Title":"ExpLicType","Name":"ExpLicType","Type":"Radio","Default":"if(c.CCType==\"Express\") then \"Enhanced\" else \"None\"","Options":["None","Premium","Standard","Enhanced"]},{"Title":"Multimedia","Name":"Multimedia","Type":"Combo","Default":"WIM","Options":["None","EIM","WIM","EIM&WIM","BSMediaRouting","MCAL"]}],
     "HiddenElements":[]
    }

我需要的只是字段名称和用户选择的值,即使我将这个json数据映射到我的 MyFieldViewModel 类,我也很困惑,仍然如何获得所选价值观?

更新2 (JSON数据映射工作)

当我改变时

    data: JSON.stringify(ko.toJSON(self))

与         数据:ko.toJSON(自我)

映射在我的控制器上运行完美,如下面的屏幕截图所示: Debug screenshot of Mapped list object from post json data

现在,问题仍然存在,发布表单的重点是使用用户在表单上的输入更新服务器,即针对每个表单字段元素的值。 如何发布表单字段的当前所选/类型值? 例如,在上面的屏幕截图中,我可以看到默认值,但不能看到当前选中的值。

1 个答案:

答案 0 :(得分:8)

要跟踪更改,您可以使用本文中的dirty flaghttp://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

创建以下视图模型:

function FormField(data) {
    var self = this;

    self.Name = ko.observable(data.Name);
    self.Type = ko.observable(data.Type);
    self.Options = ko.observableArray(data.Type != 'text' ? data.Options : []);
    self.Default = ko.observable(data.Default);
}

function ViewModel(data) {
    var self = this;

    self.Fields = ko.observableArray(ko.utils.arrayMap(data, function(item) {
        return new FormField(item);
    }));

    self.dirtyFlag = new ko.dirtyFlag(this);

    self.isDirty = ko.computed(function (){
        if (self.dirtyFlag.isDirty())
        {
            alert("Value changed!");
            // Do async update.
        }
    });
}

Html标记:

<div data-bind="foreach: Fields">
    <b data-bind="text: Name"></b>
    <!--ko if: Type() == "combo"-->
        <select data-bind="options: Options, value: Default"></select>                 <!--/ko-->
    <!--ko if: Type() == "radio"-->
        <div data-bind="foreach: Options">
            <input type="radio" value="cherry" data-bind="value: $data, checked: $parent.Default" />
            <span data-bind="text: $data"></span>
        </div>
    <!--/ko-->    
    <!--ko if: Type() == "text"-->
        <input type="text" data-bind="value: Default"></input>                 
    <!--/ko-->   
    <br/>    
</div>

这是工作小提琴:http://jsfiddle.net/vyshniakov/CWTTR/

编辑:

如果我理解正确的话,以下是您的问题的答案:

要将所有字段发布到服务器,您可以使用ko.toJSON(self)功能。您的ajax调用将如下所示:

    $.ajax({
        type: "POST",
        url: "controller/action",
        contentType: 'application/json',
        data: JSON.stringify(ko.toJSON(self)),
        success: function(result) {
            self.HiddenElements(result);
        }
    });

查看更新的小提琴,了解如何隐藏某些字段,具体取决于服务器的响应:http://jsfiddle.net/vyshniakov/CWTTR/1/