0

I'm developing an app using asp.net mvc.I'm using Code First Approach. My Goal is to develop asp.net mvc app using Knock out JS for Validation, Mapping and Binding to database. My Model class:

  public class Customers
  {
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Customer_ID { get; set; }

   [Display(Name="Customer Name")]
   public string Customer_Name { get; set; }


   [Display(Name = "Contact Name")]
   public string Contact_Name { get; set; }


   public string Address { get; set; }

   public string City { get; set; }

   [Display(Name = "Postal Code")]
   [DataType(DataType.PostalCode)]
   public string PostalCode { get; set; }

   public string Country { get; set; }
   }

The customers Controller Contains only one GET method INDEX() I have added CustomersAPIController which has HTTP METHODs for CRUD operations. The Index action method of CustomersController has view:

       @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/knockout-3.3.0.js"></script>
<script src="~/Scripts/knockout.validation.min.js"></script>
<script type="text/javascript">

    var CustomersInformationSystem = {};
    //The Model with the validation Rules
    CustomersInformationSystem.CustomersViewModel = function (customer) {
        var CustomersInfoModel = ko.validatedObservable({
            CustomerName: 
       ko.observable(customer.CustomerName).extend({required: true,
    minLength: 20,pattern:

            {
                message: 'Enter a  valid customer Name'
            }}),
            ContactName: ko.observable(customer.ContactName).extend({ 
            required: true,minLength: 20,pattern:

            {
                message: 'Enter a  valid contact Name'
            }}),
            Address: ko.observable(customer.Address).extend({required: 
         true,minLength: 20,pattern:

            {
                message: 'Enter a  valid Address '}}),
            City: ko.observable(customer.City).extend({required: 
            true,minLength: 20,pattern:

            {
                message: 'Enter a  valid city Name'
            }}),
            PostalCode: ko.observable(customer.PostalCode).extend({required: 
            true,
                minLength: 20,pattern:

                {
                    message: 'Enter a  valid Postal Code'
                }}),
            Country: ko.observable(customer.Country).extend({required: true,
                minLength: 20,pattern:

                {
                    message: 'Enter a  valid customer Name'
                }})
        });
            return CustomersInfoModel();

    };   
    CustomersInformationSystem.bindModel = function (customer) {

        // Create the view model
        CustomersInformationSystem.customerViewModel =
          CustomersInformationSystem.CustomersViewModel(customer);

        //The Validation initialization
        ko.validation.init({ messagesOnModified: false, errorClass: 
  'errorStyle', insertMessages: true });
        ko.applyBindings(this.CustomersViewModel);
    };

    //Save the Information
    CustomersInformationSystem.saveCustomer = function () {
        if (CustomersInformationSystem.CustomersViewModel.isValid()) {
            $.ajax({
                url: "/api/CustomersAPI",
                type: "POST",
                data: ko.toJSON(this),
                datatype: "json",
                contentType: 'application/json'
            }).done(function (res) {
                alert("Record Added Successfully" + res.EmpNo);
            }).error(function (err) {
                alert("Error " + err.status);
            });
        } else {
            alert("Please enter the valid data");
        }
    };



    $(document).ready(function () {
        CustomersInformationSystem.bindModel({  CustomerName: "", 
    ContactName: "", Address: "", City: "",PostalCode:"",Country:"" });
    });
</script>
<h2>Index</h2>
<style type="text/css">
    .errorStyle {
        border: 2px solid red;
        background-color: #fdd;
    }
</style>




<h1>Customer Information System</h1>
<form method="post" action="">
    <table class="table table-bordered table-condensed table-striped" 
       id="tblemp">

        <tr>
            <td>Customer Name</td>
            <td>
                <input type="text" id="Customer_Name" data-bind="value: 
        CustomerName" />
            </td>
        </tr>
        <tr>
            <td>Contact Name</td>
            <td>
                <input type="text" id="Contact_Name" data-bind="value: 
          ContactName" />
            </td>
        </tr>
        <tr>
            <td>Address</td>
            <td>
                <input type="text" id="Address" data-bind="value: Address" 
            />
            </td>
        </tr>
        <tr>
            <td>City</td>
            <td>
                <input type="text" id="City" data-bind="value: City" />
            </td>
        </tr>
        <tr>
            <td>Postal Code</td>
            <td>
                <input type="text" id="PostalCode" data-bind="value: 
          PostalCode" />
            </td>
        </tr>
        <tr>
            <td>Country</td>
            <td>
                <input type="text" id="Country" data-bind="value: Country"
                  />
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="Save" id="save"
                       data-bind="click: 
        CustomersInformationSystem.saveCustomer" class="btn btn-success" />
            </td>
            <td></td>
        </tr>
    </table>

</form>

    }

When I submit the form ,I'm not seeing either any error or the data is not being saved to the database.Please look at the Javascript Code.Please correct me.Thank you in advance.

sujay raj
  • 89
  • 11
  • Have you tried putting a break point in the controller action that is supposed to be hit when you post the data? What does the data look like when it gets to the action? Is it what you expected? – Armand Nov 13 '15 at 06:08
  • I don't think it's problem with POST method.The script is not even showing validation messages. – sujay raj Nov 13 '15 at 06:27
  • Have a look [here](http://stackoverflow.com/questions/12098029/knockout-validation-how-to-show-error-messages) to see how to show the error messages – Armand Nov 13 '15 at 06:33
  • A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll The thread '' (0x1e44) has exited with code 0 (0x0)-- – sujay raj Nov 13 '15 at 06:51
  • Not able to figure out it still – sujay raj Nov 13 '15 at 09:08
  • That error suggests there is an issue with how you are posting the data and the model binding is not able to map the form data to the C# model. It might be "processData: false" is required in the .ajax() call - see my post https://conficient.wordpress.com/2012/11/30/posting-knockout-json-data-to-webapi-httppost-methods/ - use Fiddle or similar to see what actual HTTP POST data gets sent – Quango Nov 17 '15 at 10:57

0 Answers0