简体   繁体   中英

ASP.NET MVC4 ViewModel Changetracking using knockout.js

I have a page wherein I want to know when any changes have been made to any of the field and then I will disable and enable the save button.

I am using the code below and It does not work anyone know what I am missing?

@using CirrusAdmin.Models
@model MedicineModel
@{
    ViewBag.Title = "Update Medicine";
}

<script src="@Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>

<script type="text/javascript">
    var initialData = @Html.Raw(Json.Encode(Model));

    var viewModel = {
                 item : ko.observable(initialData),
                 isDirty : ko.DirtyFlag(item)
    };

    ko.applyBindings(viewModel);
</script>


<hgroup class="title">
    <h1>@ViewBag.Title.</h1>    
</hgroup>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>        
        <ol>
            <li>
                @Html.LabelFor(m => m.Code)
                @Html.TextBoxFor(m => m.Code, new { data_bind= "value: Code", @readonly = "readonly" })
            </li>
            <li>
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name, new { data_bind = "value: Name" })
            </li>
            <li>
                @Html.LabelFor(m => m.GenericName)
                @Html.TextBoxFor(m => m.GenericName, new { data_bind = "value: GenericName" })
            </li>
        </ol>
    </fieldset>

    <input type="submit" data-bind="enable: isDirty" value="Save" />
}

    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

I think you are applying the bindings too early in the process. Try moving

 ko.applyBindings(viewModel);

below your form (ie)

@using (Html.BeginForm()) 
{
  //your form code stuff here
}
<script type="text/javascript">
 ko.applyBindings(viewModel);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM