将使用 mustache.js 呈现的 select 字段绑定到 MVC 模型

Bind select field rendered with mustache.js to MVC model

我使用 mustache.js 根据之前的 selection 渲染一个 select 场。该字段呈现正常,但是当我序列化表单以便我可以 post 它时,该字段不存在并且值没有绑定到模型。

这是小胡子模板:

<div class="col-md-8" id="controlField">
    <script id="controlTemplate" type="text/template">
        <select class="form-control" id="ItemId" {{^.}} disabled{{/.}}>
        {{#.}}
            <option value="{{Id}}">{{Description}}</option>
        {{/.}}
        </select>
    </script>
</div>

这是绑定模型的javascript:

getSubkontaApiCall(query, function(result) {
        var template = $controlTemplate.html();
        var html = Mustache.to_html(template, result);
        $controlField.html(html);
    }, function(error) {
        alert(error);
});

我正在使用 AJAX,所以我手动处理提交调用。

$form.submit(function(event) {
    event.preventDefault();
    $form = $("#mainForm"); // I added this because I cache the form when the page loads, so speed things up, but since new elements are added, I'm recaching it
    $.validator.unobtrusive.parse($form);
    $form.validate().settings.ignore = []; // using jQuery controls that hide some inputs and that's why I need this
    if ($form.valid()) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Add", "Test")',
            data: $form.serialize(),
            success: function(result) {
                $mainDiv.html(result);
                resetForm();
            },
            error: function(xhr, ajaxOptions, thrownError) {
                // TODO: handle error
            }
        });
    }
});

这就是Action的定义,剩下的动作就不是那么重要了。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Add( [Bind(Include = "ItemId, ..., ..., ...")] ItemModel model)

如何更新表单以使其识别新控件?

我发现了问题,serialize() 仅序列化具有 name 属性的输入,所以添加它就成功了。