0

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?

Nils Anders
  • 4,212
  • 5
  • 25
  • 38

3 Answers3

3
  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:

Community
  • 1
  • 1
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
  • 2
    `you remove the server view models`. Really? I have to very strongly disagree with this sentence. – Darin Dimitrov Jan 29 '13 at 07:24
  • @DarinDimitrov, if you go full out with OData/WCF Data Services and Knockout then you don't need to write much code at all. – Richard Schneider Jan 29 '13 at 07:26
  • If you go full out with OData/WCF where does the ASP.NET MVC come into the picture? I thought the OP was asking about using knockoutjs with ASP.NET MVC. – Darin Dimitrov Jan 29 '13 at 09:48
  • @DarinDimitrov very good question. You don't need it! This allows moving all the UI code to the client where it belongs. – Richard Schneider Jan 29 '13 at 09:51
  • MVC still plays an important role in things like authentication, routing, and organization. Your MVC Controllers and Methods can be a lot simpler, but it doesn't make MVC unnecessary. – Joel Cochran Jan 29 '13 at 11:20
  • @JoelCochran updated answer for your concerns on Authentication and Routing. What do you mean by Organisation? Is this where you place all the .cs files? What is this an issue? – Richard Schneider Jan 29 '13 at 11:39
  • If i using automapper to map domain model to viewmodel and viceverca, then do Format.String and other stuff likes that in viewmodel then pass it to Knockout viewmodel?? – Nils Anders Jan 29 '13 at 13:30
  • @RichardSchneider - They aren't concerns, just helpful things that MVC gives you out of the box. By organization, I mean things like Areas and file organization. Again, not an "issue", just something I like with MVC. Plus, you can do both AJAX oriented sites and still take advantage of things like ViewBag and ViewModels when it make sense. The combination is the best of both worlds. – Joel Cochran Jan 30 '13 at 13:35
0

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);
0

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).

user2626270
  • 258
  • 2
  • 6