Kokombads
Kokombads

Reputation: 460

How can I pass an object to a controller that has been bound by knockout js

here is my http post controller:

[HttpPost]
public ActionResult Create(Employee p)
{
    if (ModelState.IsValid)
    {
        Employee employee = EmployeeDataAccess.AddToDatabase(p);

        return RedirectToAction("Index", "Hr");
    }

    return View();
}

here is my view

@model TimeInTimeOut.Models.Employee

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

<table>
    <tr>
        <td><input type="text" placeholder="LastName" data-bind="value: lastName"/></td>
    </tr>
    <tr>
        <td><input type="text" placeholder="FirstName" data-bind="value: firstName"/></td>
    </tr>
    <tr>
        <td><input type="text" placeholder="MiddleName" data-bind="value: middleName"/></td>
    </tr>
    <tr>
        <td><input type="button" value="Save To Database" data-bind="click: saveToDb"/></td>
    </tr>
</table>

@section Scripts
     {
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/knockout")
    @Scripts.Render("~/Knocks/EmployeeVm.js")
}

and here is my knockout EmployeeVm.js:

$(function() {
    ko.applyBindings(EmployeeVm);

});

var EmployeeVm = {
    employeeId: ko.observable(0),
    lastName: ko.observable(''),
    firsName: ko.observable(''),
    middleName: ko.observable(''),

    saveToDb: function() {
        var self = this;

        $.ajax({
            url: '/Employee/Create',
            type: 'post',
            dataType: 'json',
            data: ko.toJSON(this),
            contentType: 'application/json',
            success: function(data) {
                alert("Successful Employee Insert");
            }
        });

    }
}

I don't know how to pass those fields into one object to the Create(Employee p). please explain in details. I'm new to js and knockout js. And also, how can I disable the button using knockout while the end-user hasn't type anything to the LastName and FirstName yet, like, it will send an alert that those fields must not be empty and will disappear once the end-user put some text to the fields?

Upvotes: 0

Views: 265

Answers (1)

gkb
gkb

Reputation: 1459

I don't know how to pass those fields into one object to the Create(Employee p)

To answer this, let us assume that your Employee looks like this -

public class Employee
{
    public string EmployeeId {get; set;}
    public string FirstName {get; set;}
    public string MiddleName {get; set;}
    public string LastName {get; set;}
}

For your controller method (which is an HttpPost method) to know that you are passing a JSON formatted Employee, you need to modify slightly the signature of the method like so -

public ActionResult Create([FromBody] Employee p)

Which tells that the Employee you need is part of the Request body and not the Query string.

And also, how can I disable the button using knockout while the end-user hasn't type anything to the LastName and FirstName yet, like, it will send an alert that those fields must not be empty and will disappear once the end-user put some text to the fields?

You need to put the required field validation for those fields -

lastName: ko.observable('').extend({required: true}),
firsName: ko.observable('').extend({required: true})

And put a computed around these observables to check if the button should be enabled -

var canSubmit = ko.computed(function() {
    return (self.lastName.isValid() && self.firstName.isValid());
});

Also, to evaluate this computed as user inputs the values for firstName and lastName, you could tell knockout to do this by adding a 'valueUpdate' attribute to your binding -

Then use enable binding to control if it should be enabled -

<td><input type="button" value="Save To Database" data-bind="click: saveToDb, enable: canSubmit"/></td>

I'm new to js and knockout js.

There is a very nice tutorial for knockout here

Upvotes: 1

Related Questions