Nils Anders
Nils Anders

Reputation: 4410

Knockout with ASP.NET MVC4

Looking to start using Knockout with ASP.NET MVC4. Have watch some examples and encountered the following questions.

  1. Today I write my view models backend, I can totally replace it with knockout view models on the client side?

  2. Is there anything like DataAnnotations in Knockout for validation?

Upvotes: 0

Views: 2083

Answers (3)

user1968030
user1968030

Reputation:

You can use this library or this

or use this samole

<script id="customMessageTemplate" type="text/html">
    <em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
    <legend>User: <span data-bind='text: errors().length'></span> errors</legend>
    <label>First name: <input data-bind='value: firstName'/></label>
    <label>Last name: <input data-bind='value: lastName'/></label>    
    <div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'>
        <label>Email: <input data-bind='value: emailAddress' required pattern="@"/></label>
        <label>Location: <input data-bind='value: location'/></label>
        <label>Age: <input data-bind='value: age' required/></label>
    </div>
    <label>
        Subscriptions: 
        <select data-bind='value: subscription, options: subscriptionOptions, optionsCaption: "Choose one..."'></select>
    </label>
    <label>Password: <input data-bind='value: password' type="password"/></label>
    <label>Retype password: <input data-bind='value: confirmPassword' type="password"/></label>
    <label>10 + 1 = <input data-bind='value: captcha'/></label>
</fieldset>
<button type="button" data-bind='click: submit'>Submit</button>
<br />
<br />
<button type="button" data-bind='click: requireLocation'>Make 'Location' required</button>

ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
    lastName: ko.observable().extend({ required: true }),
    emailAddress: ko.observable().extend({  // custom message
        required: { message: 'Please supply your email address.' }
    }),
    age: ko.observable().extend({ min: 1, max: 100 }),
    location: ko.observable(),
            subscriptionOptions: ['Technology', 'Music'],
    subscription: ko.observable().extend({ required: true }),
    password: ko.observable(),
        captcha: ko.observable().extend({  // custom validator
        validation: { validator: captcha, message: 'Please check.' }
    }),
    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};

viewModel.confirmPassword = ko.observable().extend({
    validation: { validator: mustEqual, message: 'Passwords do not match.', params: viewModel.password }
}),
viewModel.errors = ko.validation.group(viewModel);
viewModel.requireLocation = function () {
    viewModel.location.extend({ required: true });
};
ko.applyBindings(viewModel);

Upvotes: 0

user2626270
user2626270

Reputation: 258

Knockout.js is a great library. But if you ask people what to use knockout or angular. Most of them will tell you Angular.js is better, though they are very similar.

I use knockout in my projects. And there are many things that can simplify your development. For example. I use server side validation only. When user clicks on "submit", my javascript collects model and sends it to controller (asyncronously AJAX). Controller has validation, and if validation fails the response would be HTTP:500 and body will be validation result structure, that displays all errors in correct places in HTML.

From user's perspective it seems like client-side validation. You can see how it works in this example: Create Order Example (Upida.Net).

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35477

  1. Yes, you remove the server view and view models. All are now are now on the client.

  2. See Knockout validation

Also, you may want to check out OData/WCF data services (http://blogs.msdn.com/b/astoriateam/). It basically gives you a Model and Controller. With this approach you server ends up only serving static HTML pages and Model data as AJAX calls. And it also supports "paging" of data.

IMHO, this the way of the future.

Other links of interest:

Upvotes: 3

Related Questions