带有复选框绑定的Knockout数据绑定问题

时间:2016-03-25 14:43:42

标签: c# asp.net-mvc entity-framework knockout.js

我使用knockout将我的实体框架数据模型中的数据绑定到mvc视图。

尝试编辑名为active的位值的数据时遇到问题。当我编辑或创建客户端时,first和lastname列更新正常,但数据库中的位值未更改。

我共享一个名为form的视图,它将解释它是在编辑还是创建一个客户端

查看

  @using IndustryProject1._1.Extensions
@model IndustryProject1._1.Models.Client

@{
    var isCreating = Model.Id == 0;
    ViewBag.Title = (isCreating) ? "Create" : "Edit";
}

<h2>@ViewBag.Title</h2>


@using (Html.BeginForm("Create", "Clients", FormMethod.Post, new { data_bind = "submit: validateAndSave" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Client</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", data_bind = "value: client.firstname" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", data_bind = "value: client.lastname" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Active, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { @class = "form-control", data_bind = "checked: client.active" } })
                @Html.ValidationMessageFor(model => model.Active, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10" data-bind="visible: !sending()">
                <input type="submit" value="@if (isCreating)
                                            {
                                                @Html.Raw("Create")
                                            }
                                            else
                                            {
                                                @Html.Raw("Update")
                                            }"
                       class="btn btn-default"/>
            </div>

            <div class="progress" data-bind="visible: sending">
                <div class="progress-bar progress-bar-info progress-bar-striped active"
                     role="progressbar" aria-valuenow="100"
                     aria-valuemin="0" aria-valuemax="100"
                     style="width: 100%">
                    <span class="sr-only"></span>
                </div>
            </div>

        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval",
    "~/Scripts/knockout-3.4.0.js",
 "/Scripts/ViewModels/ClientFormViewModel.js")
    <script>
 var viewModel = new ClientFormViewModel(@Html.HtmlConvertToJson(Model));
 ko.applyBindings(viewModel);
    </script>
}

客户端ViewModel

function ClientFormViewModel(client) {
    var self = this;
    //used to alter page when saved succesfully
    self.saveCompleted = ko.observable(false);
    //used for progress bar
    self.sending = ko.observable(false);

    self.isCreating = client.id == 0;

    self.client = {
        id: client.id,
        firstname: ko.observable(client.firstname),
        lastname: ko.observable(client.lastname),
        active: ko.observable(client.active)
    };

    //when form is submitted it checks for jQuery validation, adds antiforgery token to ajax rquest, sends client object via ajax
    self.validateAndSave = function (form) {
        if (!$(form).valid())
            return false;

        self.sending(true);
        // include the anti forgery token
        self.client.__RequestVerificationToken = form[0].value;

        $.ajax({
            url: 'Create',
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            data: ko.toJS(self.client)
        })
        .success(self.successfulSave)
        .error(self.errorSave)
        .complete(function () { self.sending(false) });
    };

    self.successfulSave = function () {
        self.saveCompleted(true);

        $('.body-content').prepend(
        '<div class="alert alert-success"><strong>Success!</strong> The author has been saved.</div>');
        setTimeout(function () {
            if (self.isCreating)
                location.href = './';
            else
                location.href = '../';
        }, 1000);
    };
    self.errorSave = function () {
        $('.body-content').prepend(
        '<div class="alert alert-danger"><strong>Error!</strong> There was an error saving the author.</div>');
    };
}

客户端模型

public class Client
    {
        [JsonProperty(propertyName: "id")]
        public int Id { get; set; }
        [Required]
        [JsonProperty(propertyName: "firstname")]
        public string FirstName { get; set; }
        [Required]
        [JsonProperty(propertyName: "lastname")]
        public string LastName { get; set; }
        [Required]
        [JsonProperty(propertyName: "active")]
        public bool Active { get; set; }
        public virtual ICollection<Appointment> Appointments { get; set; }
    }

0 个答案:

没有答案