<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Knockout JS &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/category/knockout-js/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:19:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Knockout JS &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Knockout JS Validations, Without a Plugin and Using a Plugin</title>
		<link>https://sibeeshpassion.com/knockout-js-validations-without-a-plugin-and-using-a-plugin/</link>
					<comments>https://sibeeshpassion.com/knockout-js-validations-without-a-plugin-and-using-a-plugin/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 03 Mar 2017 17:49:21 +0000</pubDate>
				<category><![CDATA[How to]]></category>
		<category><![CDATA[Knockout JS]]></category>
		<category><![CDATA[Knockout JS Validations]]></category>
		<category><![CDATA[Knockout JS Validations Using a Plugin]]></category>
		<category><![CDATA[Knockout JS Validations Without a Plugin]]></category>
		<category><![CDATA[SImple Knockout JS Validations]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12071</guid>

					<description><![CDATA[Here we are going to see how we can implement some basic validations using Knockout JS. As we mentioned in the headline, we are going to create validation demo in two manner. Without using any plugin, our own custom way With using an existing plugin, easy way If you are totally new to Knockout JS, I stringly recommend you to read my previous post here, where I have shared some basics of Knockout JS. We will be using Visual Studio for our development. I hope you will like this. Now let&#8217;s begin. Download source code Knockout JS Validations Background As [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Here we are going to see how we can implement some basic validations using <a href="http://sibeeshpassion.com/category/client-side-technologies/knockout-js/" target="_blank">Knockout JS</a>. As we mentioned in the headline, we are going to create validation demo in two manner.</p>
<li>Without using any plugin, our own custom way</li>
<li>With using an existing plugin, easy way</li>
<p>If you are totally new to Knockout JS, I stringly recommend you to read my previous post <a href="http://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/" target="_blank">here</a>, where I have shared some basics of Knockout JS. We will be using <a href="http://sibeeshpassion.com/category/Visual-Studio/" target="_blank">Visual Studio</a> for our development. I hope you will like this. Now let&#8217;s begin.</p>
<p><strong>Download source code</strong></p>
<li>
<a href="https://code.msdn.microsoft.com/Knockout-JS-Validations-1793d978" target="_blank">Knockout JS Validations</a>
</li>
<p><strong>Background</strong></p>
<p>As I have been working in a project where we use Knockout JS, it was my duty to do some validation for an existing page. This article shows the ways I have tried to implement the same. Like I said above, using a plugin and without using a plugin. Now let&#8217;s go and implement the same in your application too. Shall we?</p>
<p><strong>Create a HTML page</strong></p>
<p>To work with Knockout JS, we need a page right. Let&#8217;s create it first. Before we do that, please do not forget to install Knockout JS and jQuery from NuGet.</p>
<div id="attachment_12074" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-12074" src="http://sibeeshpassion.com/wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-1024x537.png" alt="Installing_KnockOut_JS_from_NuGet" width="634" height="332" class="size-large wp-image-12074" srcset="/wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-1024x537.png 1024w, /wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-300x157.png 300w, /wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-768x403.png 768w, /wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-600x315.png 600w, /wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-400x210.png 400w, /wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet-1143x600.png 1143w, /wp-content/uploads/2017/03/Installing_KnockOut_JS_from_NuGet.png 1475w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12074" class="wp-caption-text">Installing_KnockOut_JS_from_NuGet</p></div>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;&lt;/title&gt;<br />
	&lt;meta charset=&quot;utf-8&quot; /&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Now create a JS file and include it in your page.</p>
<p>[js]<br />
    &lt;script src=&quot;Validations-Without-Plugin.js&quot;&gt;&lt;/script&gt;<br />
[/js]</p>
<p><strong>Let&#8217;s begin our tutorial &#8211; Knockout JS validation without using a plugin</strong></p>
<p>Open your JS file (Validations-Without-Plugin.js), this is where we are going to write our scripts. As a first step, we need to create our view model and bind it using <em>applyBindings </em>function. Am I right?</p>
<p>[js]<br />
$(function () {<br />
    function myViewModel(firstName, lastName, email) {<br />
        this.txtFirstName = ko.observable(firstName);<br />
        this.txtLastName = ko.observable(lastName);<br />
        this.txtEmail = ko.observable(email);<br />
    };<br />
    ko.applyBindings(new myViewModel(&quot;Sibeesh&quot;, &quot;Venu&quot;, &quot;sibikv4u@gmail.com&quot;));<br />
});<br />
[/js]</p>
<p>Now let create our view.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;KnockOut JS Validations&lt;/title&gt;<br />
    &lt;meta charset=&quot;utf-8&quot; /&gt;<br />
    &lt;script src=&quot;Scripts/jquery-3.1.1.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/knockout-3.4.1.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/Validations-Without-Plugin.js&quot;&gt;&lt;/script&gt;</p>
<p>&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;table&gt;<br />
        &lt;caption&gt;Knockout JS Validation&lt;/caption&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                First Name: &lt;input type=&quot;text&quot; id=&quot;txtFirstName&quot; name=&quot;txtFirstName&quot; data-bind=&#8217;value: txtFirstName&#8217; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                Last Name: &lt;input type=&quot;text&quot; id=&quot;txtLastName&quot; name=&quot;txtLastName&quot; data-bind=&#8217;value: txtLastName&#8217; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                Email: &lt;input type=&quot;text&quot; id=&quot;txtEmail&quot; name=&quot;txtEmail&quot; data-bind=&#8217;value: txtEmail&#8217; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                &lt;input type=&quot;button&quot; value=&quot;Submit&quot; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    &lt;/table&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>If you run your page, you can see the view has got updated with the values we have given in our view model (Do you remember the use if observable()?)</p>
<div id="attachment_12073" style="width: 486px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout_JS_Observables_Updated.png"><img decoding="async" aria-describedby="caption-attachment-12073" src="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout_JS_Observables_Updated.png" alt="Knockout_JS_Observables_Updated" width="476" height="464" class="size-full wp-image-12073" srcset="/wp-content/uploads/2017/03/Knockout_JS_Observables_Updated.png 476w, /wp-content/uploads/2017/03/Knockout_JS_Observables_Updated-300x292.png 300w, /wp-content/uploads/2017/03/Knockout_JS_Observables_Updated-400x390.png 400w" sizes="(max-width: 476px) 100vw, 476px" /></a><p id="caption-attachment-12073" class="wp-caption-text">Knockout_JS_Observables_Updated</p></div>
<p>So far everything is good, now it is time to update our view model and create some extenders. </p>
<blockquote><p>
Knockout JS extenders are the easy way to give some additional functionalities to your observables. It can be anything, in this case we are going to create some validations for our observables or our controls.
</p></blockquote>
<p>We can create the extenders and update the view as preceding.</p>
<p>[js]<br />
$(function () {<br />
    ko.extenders.isRequired = function (elm, customMessage) {</p>
<p>        //add some sub-observables to our observable<br />
        elm.hasError = ko.observable();<br />
        elm.message = ko.observable();</p>
<p>        //This is the function to validate the value entered in the text boxes</p>
<p>        function validateValueEntered(valEntered) {<br />
            elm.hasError(valEntered ? false : true);<br />
            //If the custom message is not given, the default one is taken<br />
            elm.message(valEntered ? &quot;&quot; : customMessage || &quot;I am required 🙁 &quot;);<br />
        }</p>
<p>        //Call the validation function for the initial validation<br />
        validateValueEntered(elm());</p>
<p>        //Validate the value whenever there is a change in value<br />
        elm.subscribe(validateValueEntered);</p>
<p>        return elm;<br />
    };</p>
<p>    ko.extenders.isEmail = function (elm, customMessage) {</p>
<p>        //add some sub-observables to our observable<br />
        elm.hasError = ko.observable();<br />
        elm.message = ko.observable();</p>
<p>        //This is the function to validate the value entered in the text boxes</p>
<p>        function validateEmail(valEntered) {<br />
            var emailPattern = /^(([^&lt;&gt;()\[\]\\.,;:\s@&quot;]+(\.[^&lt;&gt;()\[\]\\.,;:\s@&quot;]+)*)|(&quot;.+&quot;))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;<br />
            //If the value entered is a valid mail id, return fals or return true<br />
            elm.hasError((emailPattern.test(valEntered) === false) ? true : false);<br />
            //If not a valid mail id, return custom message<br />
            elm.message((emailPattern.test(valEntered) === true) ? &quot;&quot; : customMessage);<br />
        }</p>
<p>        //Call the validation function for the initial validation<br />
        validateEmail(elm());</p>
<p>        //Validate the value whenever there is a change in value<br />
        elm.subscribe(validateEmail);</p>
<p>        return elm;<br />
    };</p>
<p>    function myViewModel(firstName, lastName, email) {<br />
        this.txtFirstName = ko.observable(firstName).extend({ isRequired: &quot;You missed First Name&quot; });<br />
        this.txtLastName = ko.observable(lastName).extend({ isRequired: &quot;&quot; });<br />
        this.txtEmail = ko.observable(email).extend({ isEmail: &quot;Not a valid mail id&quot; });<br />
    };<br />
    ko.applyBindings(new myViewModel(&quot;Sibeesh&quot;, &quot;Venu&quot;, &quot;sibikv4u@gmail.com&quot;));<br />
});<br />
[/js]</p>
<p>Here <em>.extend({ isRequired: &#8220;You missed First Name&#8221; });</em> is used for calling the extenders we are just created. The first parameter is the extender name you are creating, and the second one is just a custom message. I had explained the codes with comments, if you get any issues or doubt, please feel free to ask your queries. Now it is time to update our view.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;KnockOut JS Validations&lt;/title&gt;<br />
    &lt;meta charset=&quot;utf-8&quot; /&gt;<br />
    &lt;script src=&quot;Scripts/jquery-3.1.1.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/knockout-3.4.1.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/Validations-Without-Plugin.js&quot;&gt;&lt;/script&gt;<br />
    &lt;style&gt;<br />
        .error {<br />
            color: #D8000C;<br />
            background-color: #FFBABA;<br />
            font-family: cursive;<br />
        }<br />
        table {<br />
            border: 1px solid #c71585;<br />
            padding: 20px;<br />
        }<br />
        td {<br />
            border: 1px solid #ccc;<br />
            padding: 20px;<br />
        }<br />
    &lt;/style&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;table&gt;<br />
        &lt;caption&gt;Knockout JS Validation&lt;/caption&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                First Name: &lt;input type=&quot;text&quot; id=&quot;txtFirstName&quot; name=&quot;txtFirstName&quot; data-bind=&#8217;value: txtFirstName, valueUpdate: &quot;afterkeydown&quot;&#8217; /&gt;<br />
                &lt;span class=&quot;error&quot; data-bind=&#8217;visible: txtFirstName.hasError, text: txtFirstName.message&#8217;&gt;&lt;/span&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                Last Name: &lt;input type=&quot;text&quot; id=&quot;txtLastName&quot; name=&quot;txtLastName&quot; data-bind=&#8217;value: txtLastName, valueUpdate: &quot;afterkeydown&quot;&#8217; /&gt;<br />
                &lt;span class=&quot;error&quot; data-bind=&#8217;visible: txtLastName.hasError, text: txtLastName.message&#8217;&gt;&lt;/span&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                Email: &lt;input type=&quot;text&quot; id=&quot;txtEmail&quot; name=&quot;txtEmail&quot; data-bind=&#8217;value: txtEmail, valueUpdate: &quot;afterkeydown&quot;&#8217; /&gt;<br />
                &lt;span class=&quot;error&quot; data-bind=&#8217;visible: txtEmail.hasError, text: txtEmail.message&#8217;&gt;&lt;/span&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                &lt;input type=&quot;button&quot; value=&quot;Submit&quot; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    &lt;/table&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Every observables will be having their own hasError and message properties. And have you noticed that we are usig <em>valueUpdate: &#8220;afterkeydown&#8221;</em> in each data-bind event of our control. This is for initiating validation. Now let&#8217;s run our application and see whether it is working fine or not. </p>
<div id="attachment_12075" style="width: 690px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout-JS-validation-without-a-plugin-demo.gif"><img decoding="async" aria-describedby="caption-attachment-12075" src="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout-JS-validation-without-a-plugin-demo.gif" alt="Knockout JS validation without a plugin demo" width="680" height="494" class="size-full wp-image-12075" /></a><p id="caption-attachment-12075" class="wp-caption-text">Knockout JS validation without a plugin demo</p></div>
<p><strong>Knockout JS validation using a plugin &#8211; easy way</strong></p>
<p>As we are going to use a plugn, we need to install it from the NuGet first. You can always get the plugin from <a href="https://github.com/Knockout-Contrib/Knockout-Validation" target="_blank">here</a></p>
<div id="attachment_12076" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet.png"><img decoding="async" aria-describedby="caption-attachment-12076" src="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet-1024x514.png" alt="Knockout_Validation_JS_from_NuGet" width="634" height="318" class="size-large wp-image-12076" srcset="/wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet-1024x514.png 1024w, /wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet-300x151.png 300w, /wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet-768x386.png 768w, /wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet-400x201.png 400w, /wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet-1195x600.png 1195w, /wp-content/uploads/2017/03/Knockout_Validation_JS_from_NuGet.png 1486w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12076" class="wp-caption-text">Knockout_Validation_JS_from_NuGet</p></div>
<p>Can we create our view model now?</p>
<p>[js]<br />
$(function () {<br />
    function myViewModel(firstName, lastName, email) {<br />
        this.txtFirstName = ko.observable(firstName).extend({ required: true });<br />
        this.txtLastName = ko.observable(lastName).extend({ required: false });<br />
        this.txtEmail = ko.observable(email).extend({ email: true });<br />
    };<br />
    ko.applyBindings(new myViewModel(&quot;Sibeesh&quot;, &quot;Venu&quot;, &quot;sibikv4u@gmail.com&quot;));<br />
});<br />
[/js]</p>
<p>You can see that, there is only few lines of codes when it compared to the old one we created. Now we can create our view.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;KnockOut JS Validations&lt;/title&gt;<br />
    &lt;meta charset=&quot;utf-8&quot; /&gt;<br />
    &lt;script src=&quot;Scripts/jquery-3.1.1.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/knockout-3.4.1.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/knockout.validation.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;Scripts/Validations-Plugin.js&quot;&gt;&lt;/script&gt;<br />
    &lt;style&gt;<br />
        table {<br />
            border: 1px solid #c71585;<br />
            padding: 20px;<br />
        }<br />
        td {<br />
            border: 1px solid #ccc;<br />
            padding: 20px;<br />
        }<br />
    &lt;/style&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;table&gt;<br />
        &lt;caption&gt;Knockout JS Validation&lt;/caption&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                First Name: &lt;input type=&quot;text&quot; id=&quot;txtFirstName&quot; name=&quot;txtFirstName&quot; data-bind=&#8217;value: txtFirstName&#8217; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                Last Name: &lt;input type=&quot;text&quot; id=&quot;txtLastName&quot; name=&quot;txtLastName&quot; data-bind=&#8217;value: txtLastName&#8217; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                Email: &lt;input type=&quot;text&quot; id=&quot;txtEmail&quot; name=&quot;txtEmail&quot; data-bind=&#8217;value: txtEmail&#8217; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
            &lt;td&gt;<br />
                &lt;input type=&quot;button&quot; value=&quot;Submit&quot; /&gt;<br />
            &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    &lt;/table&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Please don&#8217;t forget to include the <em>knockout.validation.js</em> in your page. If everything is ready, run your application and see the output. </p>
<div id="attachment_12077" style="width: 656px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout-JS-validation-with-plugin-demo.gif"><img decoding="async" aria-describedby="caption-attachment-12077" src="http://sibeeshpassion.com/wp-content/uploads/2017/03/Knockout-JS-validation-with-plugin-demo.gif" alt="Knockout JS validation with plugin demo" width="646" height="483" class="size-full wp-image-12077" /></a><p id="caption-attachment-12077" class="wp-caption-text">Knockout JS validation with plugin demo</p></div>
<p>That&#8217;s all for today. You can always download the source code attached to see the complete code and application. Happy coding!.</p>
<p><strong>References</strong></p>
<li><a href="http://knockoutjs.com/documentation/extenders.html" target="_blank">Knockout JS</a></li>
<li><a href="https://github.com/Knockout-Contrib/Knockout-Validation" target="_blank">Knockout-Validation Plugin</a></li>
<p><strong>See also</strong></p>
<li><a href="http://sibeeshpassion.com/category/client-side-technologies/knockout-js/" target="_blank">Articles related to Knockout JS</a></li>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/knockout-js-validations-without-a-plugin-and-using-a-plugin/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>MVC CRUD Actions Using Knockout JS</title>
		<link>https://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/</link>
					<comments>https://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 11 Dec 2016 16:13:27 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Knockout JS]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[CRUD In Knockout JS]]></category>
		<category><![CDATA[MVC And Knockout JS]]></category>
		<category><![CDATA[MVC CRUD]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11979</guid>

					<description><![CDATA[In this post we are going to create a MVC CRUD application with the help of Knockout JS. We will be using SQL database and Visual Studio for our development. If you are new to MVC, I strongly recommend you to read my previous post about MVC here. Now let&#8217;s begin. Download source code MVC CRUD Actions Using Knockout JS Introduction about Knockout JS According to Knockout JS documentation Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we are going to create a <a href="http://sibeeshpassion.com/category/MVC" target="_blank" rel="noopener">MVC</a> CRUD application with the help of <a href="http://sibeeshpassion.com/category/Knockout-JS" target="_blank" rel="noopener">Knockout JS</a>. We will be using <a href="http://sibeeshpassion.com/category/SQL" target="_blank" rel="noopener">SQL </a> database and <a href="http://sibeeshpassion.com/category/Visual-Studio/" target="_blank" rel="noopener">Visual Studio</a> for our development. If you are new to MVC, I strongly recommend you to read my previous post about MVC <a href="http://sibeeshpassion.com/category/MVC" target="_blank" rel="noopener">here</a>. Now let&#8217;s begin.</p>
<p><strong>Download source code</strong></p>
<li>
<a href="https://code.msdn.microsoft.com/MVC-CRUD-Actions-Using-fb523b40" target="_blank" rel="noopener">MVC CRUD Actions Using Knockout JS</a>
</li>
<p><strong>Introduction about Knockout JS</strong></p>
<p>According to <a href="http://knockoutjs.com/" target="_blank" rel="noopener">Knockout JS documentation</a> <strong>Knockout</strong> is a <a href="http://sibeeshpassion.com/category/JavaScript" target="_blank" rel="noopener">JavaScript</a> library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainable.</p>
<p>It has benefits as,</p>
<p><em>Pure JavaScript library</em> &#8211; works with any server or client-side technology<br />
<em>Can be added on top of your existing web application</em> without requiring major architectural changes<br />
<em>Compact</em> &#8211; around 13kb after gzipping<br />
<em>Works on any mainstream browser</em> (IE 6+, Firefox 2+, Chrome, Safari, Edge, others)<br />
<em>Comprehensive suite of specifications</em> (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms.</p>
<p><strong>Background</strong></p>
<p>As I am working on a project which uses Knockout for binding the server data, a friend of mine requested me to create a CRUD application with Knockout, so that he can easily learn it. I just accepted his request and here we are going to create a MVC CRUD application with the help of Knockout JS. I hope you will like this. </p>
<p><strong>Create an Empty MVC application</strong></p>
<p>To get started we will create an empty MVC application as follows.</p>
<div id="attachment_11980" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633.png"><img decoding="async" aria-describedby="caption-attachment-11980" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633.png" alt="add_new_empty_mvc_project" width="634" height="494" class="size-full wp-image-11980" srcset="/wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633.png 458w, /wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633-300x234.png 300w, /wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633-400x312.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11980" class="wp-caption-text">add_new_empty_mvc_project</p></div>
<p><strong>Creating database and Entity Data Model</strong></p>
<p>Here I am creating a database with name &#8220;TrialDB&#8221;, you can always create a DB by running the query given below. </p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialDB]    Script Date: 20-11-2016 03:54:53 PM ******/<br />
CREATE DATABASE [TrialDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf&#8217; , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf&#8217; , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF<br />
GO</p>
<p>USE [TrialDB]<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p><strong>Create a table</strong></p>
<p>To create a table, you can run the query below.</p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Course]    Script Date: 20-11-2016 03:57:30 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Course](<br />
	[CourseID] [int] NOT NULL,<br />
	[CourseName] [nvarchar](50) NOT NULL,<br />
	[CourseDescription] [nvarchar](100) NULL,<br />
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED<br />
(<br />
	[CourseID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>So our database is ready. Now we will create an Entity Data Model with the database we created.</p>
<div id="attachment_11981" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Entity_data_model.png"><img decoding="async" aria-describedby="caption-attachment-11981" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Entity_data_model-1024x793.png" alt="create_entity_data_model" width="634" height="491" class="size-large wp-image-11981" srcset="/wp-content/uploads/2016/12/Create_Entity_data_model-1024x793.png 1024w, /wp-content/uploads/2016/12/Create_Entity_data_model-300x232.png 300w, /wp-content/uploads/2016/12/Create_Entity_data_model-768x595.png 768w, /wp-content/uploads/2016/12/Create_Entity_data_model-400x310.png 400w, /wp-content/uploads/2016/12/Create_Entity_data_model-775x600.png 775w, /wp-content/uploads/2016/12/Create_Entity_data_model.png 1158w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11981" class="wp-caption-text">create_entity_data_model</p></div>
<p><strong>Install Knockout JS</strong></p>
<p>To install Knockout JS in your project, please right click on your project ad click on Manage Nuget Package and search for &#8216;Knockout&#8217;.</p>
<div id="attachment_11982" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Install_Knockout.png"><img decoding="async" aria-describedby="caption-attachment-11982" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Install_Knockout-1024x592.png" alt="install_knockout" width="634" height="367" class="size-large wp-image-11982" srcset="/wp-content/uploads/2016/12/Install_Knockout-1024x592.png 1024w, /wp-content/uploads/2016/12/Install_Knockout-300x173.png 300w, /wp-content/uploads/2016/12/Install_Knockout-768x444.png 768w, /wp-content/uploads/2016/12/Install_Knockout-400x231.png 400w, /wp-content/uploads/2016/12/Install_Knockout-1038x600.png 1038w, /wp-content/uploads/2016/12/Install_Knockout.png 1485w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11982" class="wp-caption-text">install_knockout</p></div>
<p>Now let us start our coding as everything is set. </p>
<p><strong>C &#8211; Create Operation</strong></p>
<p>So we are going to see the create operation, as it comes first in CRUD. Let us set up our controller first. You can see the controller code for create operation here.</p>
<p>[csharp]<br />
 // GET: Home/Create<br />
        public ActionResult Create()<br />
        {<br />
            return View();<br />
        }</p>
<p>        // POST: Home/Create<br />
        [HttpPost]<br />
        public string Create(Course course)<br />
        {<br />
            if (!ModelState.IsValid) return &quot;Model is invalid&quot;;<br />
            _db.Courses.Add(course);<br />
            _db.SaveChanges();<br />
            return &quot;Cource is created&quot;;<br />
        }<br />
[/csharp]</p>
<p>Here the first action calls the view for the create operation and the second operation insert the data to database. And _db is our entity.</p>
<p>[csharp]<br />
private readonly TrialDBEntities _db = new TrialDBEntities();<br />
[/csharp]</p>
<p>Now let&#8217;s go ahead and create view for Create operation.</p>
<p>[html]<br />
@model MVCCRUDKnockout.Models.Course</p>
<p>@{<br />
    ViewBag.Title = &quot;Create&quot;;<br />
}</p>
<p>&lt;div class=&quot;form-horizontal&quot;&gt;<br />
    &lt;h4&gt;Course&lt;/h4&gt;<br />
    &lt;hr&gt;</p>
<p>    &lt;div class=&quot;form-group&quot;&gt;<br />
        &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseName&quot;&gt;CourseName&lt;/label&gt;<br />
        &lt;div class=&quot;col-md-10&quot;&gt;<br />
            &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseName&quot; name=&quot;CourseName&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseName&quot;&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;</p>
<p>    &lt;div class=&quot;form-group&quot;&gt;<br />
        &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseDescription&quot;&gt;CourseDescription&lt;/label&gt;<br />
        &lt;div class=&quot;col-md-10&quot;&gt;<br />
            &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseDescription&quot; name=&quot;CourseDescription&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseDescription&quot;&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;</p>
<p>    &lt;div class=&quot;form-group&quot;&gt;<br />
        &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;<br />
            &lt;input type=&quot;button&quot; data-bind=&quot;click: createCourse&quot; value=&quot;Create&quot; class=&quot;btn btn-default&quot;&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;</p>
<p>&lt;div&gt;<br />
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Read&quot;)<br />
&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KOCreate.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Did you notice that we are binding data to our input controls as <em>data-bind=&#8221;value: CourseName&#8221;</em>? This value is related to the view model we are going to set, the interesting this is, the values in the model will get changed as you change the values in the input. You don&#8217;t need to add any kind of codes for that operations. </p>
<p>At last we are binding a click event as follows right?</p>
<p>[html]<br />
&lt;input type=&quot;button&quot; data-bind=&quot;click: createCourse&quot; value=&quot;Create&quot; class=&quot;btn btn-default&quot;&gt;<br />
[/html]</p>
<p>This will call the function <em>createCourse</em> which we are going to specify in our view model. Now you may be thinking what is this view model? This knockout uses MVVM pattern and now let us read some basic information provided in <a href="http://knockoutjs.com/documentation/observables.html" target="_blank" rel="noopener">Knockout JS documentation</a>.</p>
<p><strong>MVVM and View Models</strong></p>
<p>Model-View-View Model (MVVM) is a design pattern for building user interfaces. It describes how you can keep a potentially sophisticated UI simple by splitting it into three parts:</p>
<p><em>A model</em>: your application’s stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.</p>
<p><em>A view model</em>: a pure-code representation of the data and operations on a UI. For example, if you’re implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.</p>
<p>Note that this is not the UI itself: it doesn’t have any concept of buttons or display styles. It’s not the persisted data model either &#8211; it holds the unsaved data the user is working with. When using KO, your view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.</p>
<p><em>A view</em>: a visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.</p>
<p>When using KO, your view is simply your HTML document with declarative bindings to link it to the view model. Alternatively, you can use templates that generate HTML using data from your view model.</p>
<p>Now back to our Create operation, <em>KOCreate.js</em> is the file we are going to write our operation. Now please open that file and bind view model as follows.</p>
<p>[js]<br />
$(function () {<br />
    ko.applyBindings(modelCreate);<br />
});<br />
[/js]</p>
<div id="attachment_11983" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202.png"><img decoding="async" aria-describedby="caption-attachment-11983" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202.png" alt="knockout_apply_bindings" width="634" height="100" class="size-full wp-image-11983" srcset="/wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202.png 634w, /wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202-300x47.png 300w, /wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202-400x63.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11983" class="wp-caption-text">knockout_apply_bindings</p></div>
<p>Now preceding is our view model and associated functions.</p>
<p>[js]<br />
 var modelCreate = {<br />
    CourseName: ko.observable(),<br />
    CourseDescription: ko.observable(),<br />
    createCourse: function () {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/Create&#8217;,<br />
                type: &#8216;post&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                data: ko.toJSON(this), //Here the data wil be converted to JSON<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: successCallback,<br />
                error: errorCallback<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};</p>
<p>function successCallback(data) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
function errorCallback(err) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
[/js]</p>
<p>Here <em>ko.observable()</em> are special objects which can notify the changes and update the model accordingly. So if you need to update your UI automatically when the view model changes, you can use <em>observable()</em>.Now please run your view and check whether it is working fine.</p>
<div id="attachment_11984" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Page-e1481470164389.png"><img decoding="async" aria-describedby="caption-attachment-11984" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Page-e1481470164389.png" alt="create_page" width="634" height="423" class="size-full wp-image-11984" srcset="/wp-content/uploads/2016/12/Create_Page-e1481470164389.png 634w, /wp-content/uploads/2016/12/Create_Page-e1481470164389-300x200.png 300w, /wp-content/uploads/2016/12/Create_Page-e1481470164389-400x267.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11984" class="wp-caption-text">create_page</p></div>
<p><strong>R &#8211; Read operation</strong></p>
<p>As we have completed our Create operation, now it is time for Read. Please open your controller and write the actions as follows.</p>
<p>[csharp]<br />
// GET: Home<br />
        public ActionResult Read()<br />
        {<br />
            return View();<br />
        }</p>
<p>        //GET All Courses<br />
        public JsonResult ListCourses()<br />
        {<br />
            return Json(_db.Courses.ToList(), JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<p>You can create your Read view as preceding.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Read&quot;;<br />
}</p>
<p>&lt;h2&gt;Index&lt;/h2&gt;</p>
<p>&lt;p&gt;<br />
    @Html.ActionLink(&quot;Create New&quot;, &quot;Create&quot;)<br />
&lt;/p&gt;<br />
&lt;table class=&quot;table&quot;&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;<br />
            Course Name<br />
        &lt;/th&gt;<br />
        &lt;th&gt;<br />
            Course Description<br />
        &lt;/th&gt;<br />
        &lt;th&gt;&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    &lt;tbody data-bind=&quot;foreach: Courses&quot;&gt;<br />
    &lt;tr&gt;<br />
        &lt;td data-bind=&quot;text: CourseName&quot;&gt;&lt;/td&gt;<br />
        &lt;td data-bind=&quot;text: CourseDescription&quot;&gt;&lt;/td&gt;<br />
        &lt;td&gt;<br />
            &lt;a data-bind=&quot;attr: { &#8216;href&#8217;: &#8216;@Url.Action(&quot;Edit&quot;, &quot;Home&quot;)/&#8217; + CourseID }&quot; class=&quot;btn-link&quot;&gt;Edit&lt;/a&gt;<br />
            &lt;a data-bind=&quot;attr: { &#8216;href&#8217;: &#8216;@Url.Action(&quot;Delete&quot;, &quot;Home&quot;)/&#8217; + CourseID }&quot; class=&quot;btn-link&quot;&gt;Delete&lt;/a&gt;<br />
        &lt;/td&gt;<br />
    &lt;/tr&gt;<br />
    &lt;/tbody&gt;<br />
&lt;/table&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KORead.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here we are using <em>data-bind=&#8221;foreach: Courses&#8221;</em> for looping through our model we are going to create now. So shall we do that? Please create a JS file with name <em>KORead.js</em> and add the following code.</p>
<p>[js]<br />
$(function () {<br />
    ko.applyBindings(modelView);<br />
    modelView.viewCourses();<br />
});</p>
<p>var modelView = {<br />
    Courses: ko.observableArray([]),<br />
    viewCourses: function () {<br />
        var thisObj = this;<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/ListCourses&#8217;,<br />
                type: &#8216;GET&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: function (data) {<br />
                    thisObj.Courses(data); //Here we are assigning values to KO Observable array<br />
                },<br />
                error: function (err) {<br />
                    alert(err.status + &quot; : &quot; + err.statusText);<br />
                }<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};<br />
[/js]</p>
<p>Here goes the output.</p>
<div id="attachment_11985" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Read_Page.png"><img decoding="async" aria-describedby="caption-attachment-11985" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Read_Page-1024x299.png" alt="read_page" width="634" height="185" class="size-large wp-image-11985" srcset="/wp-content/uploads/2016/12/Read_Page-1024x299.png 1024w, /wp-content/uploads/2016/12/Read_Page-300x88.png 300w, /wp-content/uploads/2016/12/Read_Page-768x225.png 768w, /wp-content/uploads/2016/12/Read_Page-400x117.png 400w, /wp-content/uploads/2016/12/Read_Page.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11985" class="wp-caption-text">read_page</p></div>
<p>Now it is time for Update operation. Are you ready?</p>
<p><strong>U &#8211; Update operation</strong></p>
<p>As we did for the above two operation, let us create some actions in our controller first. </p>
<p>[csharp]<br />
// GET: Home/Edit/5<br />
        public ActionResult Edit(int? id)<br />
        {<br />
            if (id == null)<br />
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);<br />
            var course = _db.Courses.Find(id);<br />
            if (course == null)<br />
                return HttpNotFound();<br />
            var serializer = new JavaScriptSerializer();<br />
            ViewBag.SelectedCourse = serializer.Serialize(course);<br />
            return View();<br />
        }</p>
<p>        // POST: Home/Update/5<br />
        [HttpPost]<br />
        public string Update(Course course)<br />
        {<br />
            if (!ModelState.IsValid) return &quot;Invalid model&quot;;<br />
            _db.Entry(course).State = EntityState.Modified;<br />
            _db.SaveChanges();<br />
            return &quot;Updated successfully&quot;;<br />
        }<br />
[/csharp]</p>
<p>Here the first action with parameter ID is called whenever a user click on Edit link from the table we created. And we are setting the queried data to <em>ViewBag</em> so that we can use it for our related operation. For now, we can create a view as follows.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Edit&quot;;<br />
}</p>
<p>&lt;h2&gt;Edit&lt;/h2&gt;</p>
<p>@using (Html.BeginForm())<br />
{<br />
    @Html.AntiForgeryToken()</p>
<p>    &lt;div class=&quot;form-horizontal&quot;&gt;<br />
        &lt;h4&gt;Course&lt;/h4&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseName&quot;&gt;CourseName&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseName&quot; name=&quot;CourseName&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseName&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseDescription&quot;&gt;CourseDescription&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseDescription&quot; name=&quot;CourseDescription&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseDescription&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;<br />
                &lt;input type=&quot;button&quot; data-bind=&quot;click: updateCourse&quot; value=&quot;Update&quot; class=&quot;btn btn-default&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
}<br />
&lt;script type=&quot;text/javascript&quot;&gt;<br />
    var selectedCourse = &#8216;@Html.Raw(ViewBag.selectedCourse)&#8217;;<br />
&lt;/script&gt;<br />
&lt;div&gt;<br />
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Read&quot;)<br />
&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KOUpdate.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>And create a JS with name <em>KOUpdate.js</em> and add the following code. </p>
<p>[js]<br />
var parsedSelectedCourse = $.parseJSON(selectedCourse);<br />
$(function () {<br />
    ko.applyBindings(modelUpdate);<br />
});</p>
<p>var modelUpdate = {<br />
    CourseID: ko.observable(parsedSelectedCourse.CourseID),<br />
    CourseName: ko.observable(parsedSelectedCourse.CourseName),<br />
    CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),<br />
    updateCourse: function () {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/Update&#8217;,<br />
                type: &#8216;POST&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                data: ko.toJSON(this),<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: successCallback,<br />
                error: errorCallback<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};</p>
<p>function successCallback(data) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
function errorCallback(err) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
[/js]</p>
<p>Now, run your application and see the Edit/Update operation.</p>
<div id="attachment_11986" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Edit_Page-e1481471984157.png"><img decoding="async" aria-describedby="caption-attachment-11986" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Edit_Page-e1481471984157.png" alt="edit_page" width="634" height="432" class="size-full wp-image-11986" srcset="/wp-content/uploads/2016/12/Edit_Page-e1481471984157.png 634w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-300x204.png 300w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-320x218.png 320w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-160x110.png 160w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-400x273.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11986" class="wp-caption-text">edit_page</p></div>
<p><strong>D &#8211; Delete operation</strong></p>
<p>So our last operation, Delete. Let&#8217;s edit our controller as follows. </p>
<p>[csharp]<br />
// GET: Home/Delete/5<br />
        public ActionResult Delete(int? id)<br />
        {<br />
            if (id == null)<br />
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);<br />
            var course = _db.Courses.Find(id);<br />
            if (course == null)<br />
                return HttpNotFound();<br />
            var serializer = new JavaScriptSerializer();<br />
            ViewBag.SelectedCourse = serializer.Serialize(course);<br />
            return View();<br />
        }</p>
<p>        // POST: Home/Delete/5<br />
        [HttpPost, ActionName(&quot;Delete&quot;)]<br />
        public string Delete(Course course)<br />
        {<br />
            if (course == null) return &quot;Invalid data&quot;;<br />
            var getCourse = _db.Courses.Find(course.CourseID);<br />
            _db.Courses.Remove(getCourse);<br />
            _db.SaveChanges();<br />
            return &quot;Deleted successfully&quot;;<br />
        }<br />
[/csharp]</p>
<p>The code looks exactly same as our update operation, so no explanation. Still if you get any issues, please ask. Now let us create our view.</p>
<p>[html]<br />
@model MVCCRUDKnockout.Models.Course</p>
<p>@{<br />
    ViewBag.Title = &quot;Delete&quot;;<br />
}</p>
<p>&lt;h2&gt;Delete&lt;/h2&gt;</p>
<p>&lt;h3&gt;Are you sure you want to delete this?&lt;/h3&gt;<br />
@using (Html.BeginForm())<br />
{<br />
    @Html.AntiForgeryToken()</p>
<p>    &lt;div class=&quot;form-horizontal&quot;&gt;<br />
        &lt;h4&gt;Course&lt;/h4&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseName&quot;&gt;CourseName&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseName&quot; name=&quot;CourseName&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseName&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseDescription&quot;&gt;CourseDescription&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseDescription&quot; name=&quot;CourseDescription&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseDescription&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;<br />
                &lt;input type=&quot;button&quot; data-bind=&quot;click: deleteCourse&quot; value=&quot;Delete&quot; class=&quot;btn btn-default&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
}<br />
&lt;script type=&quot;text/javascript&quot;&gt;<br />
    var selectedCourse = &#8216;@Html.Raw(ViewBag.selectedCourse)&#8217;;<br />
&lt;/script&gt;<br />
&lt;div&gt;<br />
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Read&quot;)<br />
&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KODelete.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>And you can always create our knockout codes as preceding.</p>
<p>[js]<br />
var parsedSelectedCourse = $.parseJSON(selectedCourse);<br />
$(function () {<br />
    ko.applyBindings(modelDelete);<br />
});</p>
<p>var modelDelete = {<br />
    CourseID: ko.observable(parsedSelectedCourse.CourseID),<br />
    CourseName: ko.observable(parsedSelectedCourse.CourseName),<br />
    CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),<br />
    deleteCourse: function () {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/Delete&#8217;,<br />
                type: &#8216;POST&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                data: ko.toJSON(this),<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: successCallback,<br />
                error: errorCallback<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};</p>
<p>function successCallback(data) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
function errorCallback(err) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
[/js]</p>
<p>If everything goes fine, you will get a page as follows.</p>
<div id="attachment_11987" style="width: 867px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Delete_Page-e1481472332467.png"><img decoding="async" aria-describedby="caption-attachment-11987" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Delete_Page-e1481472332467.png" alt="delete_page" width="857" height="591" class="size-full wp-image-11987" srcset="/wp-content/uploads/2016/12/Delete_Page-e1481472332467.png 518w, /wp-content/uploads/2016/12/Delete_Page-e1481472332467-300x207.png 300w, /wp-content/uploads/2016/12/Delete_Page-e1481472332467-160x110.png 160w, /wp-content/uploads/2016/12/Delete_Page-e1481472332467-400x276.png 400w" sizes="(max-width: 857px) 100vw, 857px" /></a><p id="caption-attachment-11987" class="wp-caption-text">delete_page</p></div>
<p>That&#8217;s all for today. You can always download the source code attached to see the complete code and application. Happy coding!.</p>
<p><strong>References</strong></p>
<li><a href="http://knockoutjs.com/index.html" target="_blank" rel="noopener">Knockout JS</a></li>
<li><a href="http://knockoutjs.com/documentation/observables.html" target="_blank" rel="noopener">Knockout JS Observables</a></li>
<p><strong>See also</strong></p>
<li><a href="http://knockoutjs.com/documentation/links.html" target="_blank" rel="noopener">External links and tutorials</a></li>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
