Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Friday, September 25, 2015

Creating a very simple Ajax Form in ASP.NET MVC 4

In this post, I am going to demonstrate how to create a simple Ajax Form in ASP.NET MVC 4 application using Visual Studio.  I am using Visual Studio 2015 but this should work with VS 2013 too. We are going to submit information about a person using some ajax and with minimum use of javascript.  There is javascript used but we are taking advantage of the wonderful tooling and template benefits of ASP.NET MVC4.  I assume you know some basics of ASP.NET MVC 4 but to get started you create a default asp.net mvc 4 application inside visual studio.

Before diving right into code you may want to check the pre-requisites section below.

PREREQUISITES

Packages.

 You will need if not already installed jQuery, jQuery.UI.Combined, jQuery.Validation, Microsoft.jQuery.Unobtrusive.Ajax, Microsoft.jQuery.Unobtrusive.Validation. Below is how my packages look like.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.4.1.9004" targetFramework="net451" />
  <package id="bootstrap" version="3.0.0" targetFramework="net451" />
  <package id="EntityFramework" version="6.1.1" targetFramework="net451" />
  <package id="jQuery" version="1.10.2" targetFramework="net451" />
  <package id="jQuery.UI.Combined" version="1.11.2" targetFramework="net451" />
  <package id="jQuery.Validation" version="1.13.0" targetFramework="net451" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.2" targetFramework="net451" />
  <package id="Microsoft.AspNet.Razor" version="3.2.2" targetFramework="net451" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.2" targetFramework="net451" />
  <package id="Microsoft.jQuery.Unobtrusive.Ajax" version="3.2.2" targetFramework="net451" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.2" targetFramework="net451" />
  <package id="Microsoft.Owin" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Twitter" version="2.1.0" targetFramework="net451" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net451" />
  <package id="Modernizr" version="2.6.2" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net451" />
  <package id="Owin" version="1.0" targetFramework="net451" />
  <package id="Respond" version="1.2.0" targetFramework="net451" />
  <package id="WebGrease" version="1.5.2" targetFramework="net451" />
</packages>

Bundles

 public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive-ajax*"));

bundles.Add(new ScriptBundle("~/bundles/jqueryui")
.Include("~/Scripts/jquery-ui-*"));

bundles.Add(new StyleBundle("~/Content/jquerycss")
.Include("~/Content/themes/base/datepicker.css"));

bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));

// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = true;
}
}

Let’s dive in.


First we create a person class i.e model in the models folder inside your application. Notice the data annotations used to trigger form validation. These will be triggered on the client side when the user enters invalid information. Most of them are self explanatory however special mention to the confirm password field. It is so easy to do password confirmation here.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AspNetAjaxForm.Models
{
public class Person
{
[Required()]
[DataType(DataType.Text)]
[StringLength(50, MinimumLength = 3)]
public string FirstName { get; set; }

[Required()]
[DataType(DataType.Text)]
[StringLength(50, MinimumLength = 3)]
public string LastName { get; set; }

[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }

[Required]
public DateTime BirthDate { get; set; }

[DataType(DataType.Text)]
[StringLength(50,MinimumLength=6)]
[Required]
public string Username { get; set; }

[DataType(DataType.Password)]
[StringLength(255, MinimumLength = 8)]
[Required]
public string Password { get; set; }

[Compare("Password")]
[DataType(DataType.Password)]
[StringLength(255, MinimumLength=8)]
public string ConfirmPassword { get; set; }
}
}

Next we will create Register.cshtml page as shown below inside Views/Home folder.  For explanation see paragraph below code

@model AspNetAjaxForm.Models.Person
@{
ViewBag.Title = "Register";
}
<h2>Register</h2>
<div id="register-main">
<div id="register-main-loading-img">
<img id="loading-img" alt="loading" src="~/Content/loadingAnimation.gif">
</div>
@Html.Partial("_RegisterForm",Model)
</div>
@section scripts
{
<script type="text/javascript">
$(document).on('focus', '[data-date="birthdate"]', function () {
$(this).datepicker({
changeMonth: true,
changeYear: true
});
});
</script>
}

In the code above we specify that this form will take in strongly typed model Person. In the register-main div we have two things, one is loading image which is a spinning .gif image that you can easily get from internet and the other is a Partial view called _RegisterForm.cshtml that accepts our Model object. We will create _RegisterForm in the next step.  In the Scripts section we use Jquery to configure our date picker to show month and year field to select Birthdate. Lets’ create _RegisterForm view using the create template with Person as strongly typed object.  Now I have modified the form to use Ajax.BeginForm.  See description of the code below.

@model AspNetAjaxForm.Models.Person

<div id="ajaxForm">
@using (Ajax.BeginForm("Register", "Home", null,
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.ReplaceWith,
UpdateTargetId = "ajaxForm",
LoadingElementId = "register-main-loading-img"
}))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Person</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.BirthDate, new { htmlAttributes = new { @class = "form-control", data_date = "birthdate" } })
@Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>
</div>

In the above code, first line is obvious it takes in Person object. We wrap everything into ajaxForm div. The key parts here are as follows:


1. Using Ajax.BeginForm allows us submit form using Ajax.  The parameters say that when I click on the submit button please post this form using “Register” action on the “Home” controller which accepts “POST” request. After the form is submitted replace the contents of “ajaxForm” div with result of request and while you process the request display the loading image we specified earlier. 


2. Everything inside div form-horizontal is created using create a new asp.net mvc 4 view with a strongly typed model of type person. I modified the Birthdate field to take in the jquery ui date picker pay attention to the data_date attribute eg. data_date = "birthdate" we had inside the Register page.


Now we are going to see how everything clubs together. Until now you may be a bit lost. So lets check out our controller.  In the home controller create following methods.

           [HttpGet]
public ActionResult Register()
{
return View(new Person());
}

[HttpPost]
public async Task<PartialViewResult> Register(Person person)
{
await Task.Delay(1000);
if ((new string[] {"mitul1","mitul11","mitul12","mitul13"}).Contains(person.Username))
{
ModelState.AddModelError("Username", String.Format("username {0} is already taken", person.Username));
}
if (ModelState.IsValid)
{
return PartialView("_RegistrationResult");
}
return PartialView("_RegisterForm", person);
}

When you run the application and navigate to /Home/Register page it will hit the first Register method and display the Register.cshtml view. And inside Register.cshtml we have _RegisterFrom.cshtml partial view which will ultimately render the form.  After filling the form out when you click on the submit button the second Register method is called that takes in a Person object. This register method returns a PartialView in both the cases 1. if the form is successful 2. if the form has errors. Lets’ understand the second Register method in a little bit more detail.


1. This method uses async and await since you may be submitting the form to a database or checking validation against a web service asynchronously.  Special notice – See the async keyword on the method signature and because of that we cannot just return PartialViewResult we have decorate the method signature with Task<PartialViewResult>.  For demo purposes, I am using await Task.Delay(1000) instead of an async web call.


2. The first if statement checks if the username is already taken or not. This is just for demo purpose but you may have some complex validation on the server side and if any field is invalid then you want to throw that error back and the user should see it below that field. See the image below. You do that by using the ModelState.AddModelError method which takes in field name and error message. In our case we wanted to display that this username is already taken so we have specified ModelState.AddModelError(“username”,String.Format(”username {0} is already taken”,person.username);  Because of this statement our person model that was submitted by the user is invalidated and we return the same _RegisterForm.cshtml Partial view with person model.


image


3. If the model was valid then we enter into the second if statement and submit our person to a database or call a web service. Based upon you business logic you can do other things like if the form was unsuccessful show different message etc. In our case we are showing a partial view called _RegistrationResult.cshtml. You can modify this view to display either confirmation or error message.


Last but not the least to show stuff properly I am using following CSS.

#register-main{
position:relative;
border:3px solid green;
z-index:10;
}
#register-main-loading-img{
display:none;
position:absolute;
z-index:1;
top:0px;
left:0px;
width:100%;
height:100%;
border:3px solid orange;
background-color:rgba(216, 213, 213, 0.89);
}
#loading-img{
border:3px solid blue;
display:block;
position:relative;
width:100px;
height:100px;
margin-left:auto;
margin-right:auto;
top:50%;
}

 

So that’s about it. If you like this post of have any comments leave in the comments section.

 

 

Friday, November 22, 2013

Show selected item details from Autocomplete dropdownlist of jQuery using PartialView

This is a continuation of a series around Autocomplete using jQuery in Asp.net MVC4.

1. Implement Autocomplete using jQuery UI inside Asp.Net MVC4 Application

2. Show selected item details from Autocomplete dropdownlist of jQuery UI – (using Knockout)

3. Show selected item details from Autocomplete dropdownlist of jQuery UI – (using PartialView)

In the last post we looked at how to display details about a selected person from the dropdownlist of jQuery UI Autocomplete using Knockout.js. Knockout.js allowed us to databind our ViewModel with our view.  In this post we are going to look at how to do show details of a person but using a PartialView. 

1. Right click on the Home folder>Add>View.

image

2. Type the name of the view as _Person

image

3. Create another method named GetPerson just like the following but this one returns a PartialViewResult instead of JsonResult.  And in our select statement of LINQ query we are return a custom class with all the properties.  We had to do otherwise we won’t be able to strongly type our view.  For demo purposes I have created the class in the same class as the controller but in real world application I create separate ViewModel folder and create classes there.

[HttpGet]
public PartialViewResult GetPerson(int id)
{
var user = (from p in db.People
join e in db.Employees
on p.BusinessEntityID equals e.BusinessEntityID
join be in db.BusinessEntityAddresses on p.BusinessEntityID equals be.BusinessEntityID
join ad in db.Addresses on be.AddressID equals ad.AddressID
join st in db.StateProvinces on ad.StateProvinceID equals st.StateProvinceID
where p.BusinessEntityID == id
select new PersonDetail
{
Id = p.BusinessEntityID,
FullName = p.LastName + ", " + p.FirstName,
LastName = p.LastName,
FirstName = p.FirstName,
JobTitle = e.JobTitle,
HireDate = e.HireDate,
AddressLine1 = ad.AddressLine1,
City = ad.City,
PostalCode = ad.PostalCode,
State = st.Name
}).ToList().First();
if (user == null)
{
HttpNotFound();
}
return PartialView("_Person", user);
}

Add the following class for PersonDetail below the controller class in your HomeController.

public class PersonDetail
{
public int Id { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string JobTitle { get; set; }
public DateTime HireDate { get; set; }
public string AddressLine1 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string State { get; set; }
}

Let's make sure our PartialView _Person.cshtml accepts our model of type PersonDetail.

@model AspNetDemo06.Controllers.PersonDetail
<p>@Model.Id </p>
<p>@Model.FullName </p>
<p>@Model.LastName </p>
<p>@Model.FirstName </p>
<p>@Model.JobTitle </p>
<p>@Model.HireDate </p>
<p>@Model.AddressLine1 </p>
<p>@Model.City = ad.City </p>
<p>@Model.PostalCode </p>
<p>@Model.State </p>

Finally fix few things to fix in our Index.cshtml page. First create a div with id selectedPerson.

<div id="selectedPerson">

</div>

Then in our javascript code, first instead of FindPerson change it to GetPerson. Then in the success method of ajax call just replace the div with the returned partial view.

 $(document).ready(function () {
$("#SearchString").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Find",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
firstname: item.firstname,
lastname: item.lastname
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (even, ui) {
var businessEntityId = ui.item.id;
$.ajax({
url: "/Home/GetPerson",
type: "GET",
data: { "id": businessEntityId}
}).done(function () {
}).success(function (person) {
$("#selectedPerson").html(person);
});
}
});
});

In the above code line 36 the person object is our partial view that we inserting in the div of id selectedPerson.


image

Monday, November 18, 2013

Show selected item details after selecting an item from autocomplete dropdownlist using Knockout.js

This is a continuation of previous post where we looked at how to implement autocomplete functionality into Asp.net MVC 4 application using jQuery UI and Ajax.  In the previous post when you selected a particular user it redirected you to a different page.  What if we want to show information about that user on the same page without any page refresh.  In this post we are going to do exactly the same thing.  Well there are many ways to do this but I want to show you the one using Knockout.js. To use Knockout.js first include it in our BundleConfig.cs  

bundles.Add(new ScriptBundle("~/bundles/knockout").Include("~/Scripts/knockout-*"));

Second lets tell our _layout.cshtml page to load knockout.

<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/knockout")
@RenderSection("scripts", required: false)
</body>

Add the following javascript below the autocomplete method in Index.cshtml page. This is a PersonViewModel which has properties like LastName, FirstName and BusinessEntityID.

 
//ViewModels Knockout
function PersonViewModel(data) {
this.LastName = ko.observable(data.lastname);
this.FirstName = ko.observable(data.firstname);
this.BusinessEntityId = ko.observable(data.id);
}

We created a ViewModel for the Person Object called PersonViewModel. And ko.observable(data.lastname) means that lastname is an observable property. Next add the following div section where we are going to display selected person’s information.  Inside the span tag see the data-bind=”text: LastName” it will be replaced by the LastName returned from our select function inside autocomplete.

<div style="display: none;" data-bind="visible: true">
<span data-bind="text: LastName"></span>
<span data-bind="text: FirstName"></span>
</div>

In this post I want to just focus on people who are employees. So lets make sure we allow users to search just for Employees. Make appropriate changes suggested below

[HttpPost]
public JsonResult Find(string prefixText)
{
var suggestedUsers = from x in db.People
where x.LastName.StartsWith(prefixText) && x.PersonType == "EM"
select new {
id = x.BusinessEntityID,
value = x.LastName + ", " + x.FirstName,
firstname = x.FirstName,
lastname = x.LastName};
var result = Json(suggestedUsers.Take(5).ToList());
return result;
}

One last thing before we run our application. Replace the window.location.href line with  ko.applyBindings(new PersonViewModel(ui.item));  This will databind our selected person to the datatemplate shown above.

@section scripts{
<script type="text/javascript">
//Javascript function to provide AutoComplete and Intellisense feature for finding Users.
$(document).ready(function () {
$("#SearchString").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Find",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
firstname: item.firstname,
lastname: item.lastname
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (even, ui) {
ko.applyBindings(new PersonViewModel(ui.item));
}
});
});
//ViewModels Knockout
function PersonViewModel(data) {
this.LastName = ko.observable(data.lastname);
this.FirstName = ko.observable(data.firstname);
this.BusinessEntityId = ko.observable(data.id);
}
</script>
}

image


I just wanted to show that it could be done with Knockout. At this point our search button is non-functional. We will make it functional later. One thing to notice here is that the information about the selected user is grabbed from the initial query we did to find suggested users.  To bring in more information we would have to adjust our LINQ query.  And I know what you are thinking right now, “But Mitul, that would bring in all the unnecessary information about other users in which we are not interested.” So we are going to write another method in our HomeController to bring in information just about that selected person. Before doing that let’s update our model to bring in additional information about our selected person.


Open the ADworks.edmx file inside our Models folder and then click anywhere next to the entity and select “Update Model from Database


image


And then check on these entities Employee, Address, BusinessEntityAddress, StateProvince. 


image

Now FindPerson method will return detailed information about the selected person.
        [HttpGet]
public JsonResult FindPerson(int id)
{
var user = (from p in db.People
join e in db.Employees
on p.BusinessEntityID equals e.BusinessEntityID
join be in db.BusinessEntityAddresses on p.BusinessEntityID equals be.BusinessEntityID
join ad in db.Addresses on be.AddressID equals ad.AddressID
join st in db.StateProvinces on ad.StateProvinceID equals st.StateProvinceID
where p.BusinessEntityID == id
select new
{
Id = p.BusinessEntityID,
FullName = p.LastName + ", " + p.FirstName,
LastName = p.LastName,
FirstName = p.FirstName,
JobTitle = e.JobTitle,
HireDate = e.HireDate,
AddressLine1 = ad.AddressLine1,
City = ad.City,
PostalCode = ad.PostalCode,
State = st.Name
}).ToList().First();
if (user == null)
{
HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}

Inside our select function of AutoComplete we are going to make an ajax call [line 31] to this method passing in the BusinessEntityID [line 35] for the Person to FindPerson method [line 33]. Also I have made changes to the PersonViewModel to reflect all the properites returned from the FindPerson method.

@section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#SearchString").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Find",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
firstname: item.firstname,
lastname: item.lastname
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (even, ui) {
var businessEntityId = ui.item.id;
$.ajax({
url: "/Home/FindPerson",
type: "GET",
data: { "id": businessEntityId}
}).done(function () {
}).success(function (person) {
ko.applyBindings(new PersonViewModel(person));
});
}
});
});
//Person Detailed View Model
function PersonViewModel(p) {
this.Id = ko.observable(p.Id);
this.FullName = ko.observable(p.FullName);
this.LastName = ko.observable(p.LastName);
this.FirstName = ko.observable(p.FirstName);
this.JobTitle = ko.observable(p.JobTitle);
this.HireDate = ko.observable(p.HireDate);
this.AddressLine1 = ko.observable(p.AddressLine1);
this.City = ko.observable(p.City);
this.PostalCode = ko.observable(p.PostalCode);
this.State = ko.observable(p.State);
}
</script>
}

Finally lets update our div to reflect all the udpated user properties.

<div style="display: none;" data-bind="visible: true">
FullName:<span data-bind="text: FullName"></span>
<br/> LastName:<span data-bind="text: LastName"></span>
<br/> FirstName:<span data-bind="text: FirstName"></span>
<br/> HireDate:<span data-bind="text: HireDate"></span>
<br/> Job Title:<span data-bind="text: JobTitle"></span>
<br/> AddressLine1: <span data-bind="text: AddressLine1"></span>
<br/> City: <span data-bind="text: City"></span>
<br/> PostalCode: <span data-bind="text: PostalCode"></span>
<br/> State: <span data-bind="text: State"></span>
</div>

Run the application and search a particular user.


image


In this post, we looked at how to show selected user’s information after search for a user using jQuery UI’s autocomplete method.  Initially to display the selected user we simply data binded the object returned by the select object, we didn’t went to server to find more information.  In the final attempt we did another ajax call to the server to find more information about the user.  In the next post we will look into how to show detailed information about a person using a PartialView. 

Sunday, April 7, 2013

How to do Ajax in Asp.Net MVC4 Application?

In this post, I am going to show you how to do Ajax in an Asp.net MVC4 Application using C#.  It is very easy to create a very simple Ajax demo up and running.  Here are few things you need in order to get basic Ajax demo running in your application.  The complete source code for this application is available on my gitHub account.

0. Create basic Asp.net MVC4 application using VS2012
1. You need an Ajax.ActionLink in one of your views
2. Public Method that will return a Partial View
3. PartialView with some content

Open Index.cshtml and remove all the content and paste Ajax.ActionLink as below.  Ajax.ActionLink has 12 overloads (msdn link) to do Ajax and all of them are very self explanatory.  In the code below, I am passing in the text to display as link text, the controller action to hit, and Ajax Options that’s it. 
We need a div whose content we wish to replace or the target location where we wish to replace the contents.
Then we need a public method inside our home controller that will return a partial view with some data in it.  You can pass data to the Partial View using a ViewBag.  As in our case I am using ViewBag.Tiffin variable to hold that data and retrieve inside Partial View. Next in our Partial View we retrieve it.
Hit F5 and click on the link to see what happens.  All of the text will be replaced if you created a default Asp.net MVC4 Internet application.  Because by default Asp.net Template for MVC4 Internet Application doesn’t load the Jquery Validation bundle to do Unobtrusive JavaScript.  Include this line @Scripts.Render("~/bundles/jqueryval") in your _layout.cshtml page and you are all good to go.  Run again and you should see the output.

You might be curious to ask why are you using a POST instead of GET inside Ajax.ActionLink? Because depending on which browser you are running it will cache the response and will not trigger an ajax request every time you wish to do Ajax.  To overcome this problem you can disable cache for just that method use GET in Ajax.ActionLink

I have recorded a screencast video to show upto this point. Check it out and if you have any feedback let me know.
Now moving on to some more stuff like how can we put animated gifs showing that something is running.  That is actually even more easy.  For this purpose we are going to use few more attributes of AjaxOptions object.  This object has some events like OnCompleted, OnBegin, OnSuccess, OnFailure and we will assign javascript functions to them.  So when we trigger a ajax request then OnBegin function we will load the gif and OnCompleted we will hide the image. 
What about passing Parameters? For this we will use another overloaded method of Ajax.ActionLink which will pass routeparameters to our public method.  We are going to change our public method and Ajax.ActionLink as shown in the code below.
Ok I get it but what about some HtmlAttributes?  Actually there is very easy you use another overload of Ajax.ActionLink and you can pass in an anonymous object with values to it.  There are different options you can consider for HtmlAttributes. And also what about jQuery mobile data-role attribtues? For jQuery data attributes you will have to use _ instead of - as shown below.  Alright but now I want to implement Async and Await into this mix how can I do that?  Hmmm. For this we will have to modify our public method inside our controller to return Task of type PartialViewResult.  That is pretty easy too.
Oh! But I am told to just use jQuery to do Ajax then you have be a little bit careful. Please check your jQuery version. If you have jQuery 1.7 then Ajax is done differently and jQuery 1.9 does little bit differently. I am using 1.9 for this demo. There is a difference where you detect start and success events. You attach these events to the document object (see upgrade guide).


What-If Error
Why Ajax is still not working out for me? Here are some very common issues which I ran into while learning Ajax in MVC4 application. 

1. Always debug using Internet Explorer.  If you run your application then Chrome will show you red error count only if you inspect the page but will happily show you the page.  Compare this to Internet Explorer it will give you Microsoft JavaScript Runtime Error.  Doing a quick StackOverflow search will give you most of the common problems’ solutions.

2. Check if you have loaded Jquery Validation bundle

3. Check if you are even loading jQuery or not. Actually this should be number 0.

4. Check if you are loading multiple versions of Jquery or validation, if yes then deletes older ones.

5. Open up fiddler to see what is going on. If I am working with web then I have fiddler open by default most of the times. And it has affected my debugging skills.

6. Put breakpoints as this is very basic debugging skill.

7. Try deleting packages for jQuery and delete related entry in packages.config and again install those packages using Nuget.

8.  The complete source code for this application and demo is at gitHub.  Check this link

Thursday, October 4, 2012

Navigate List of items with Up Down arrow using jQuery in Asp.Net MVC 4 app

This is a continuation from my previous post which demonstrated how to create a simple ASP.NET MVC 4 application with Entity Framework using Adventure Works 2008 Database and Visual Studio 2012.   In this post, I will show you how to navigate our list of products using up and down arrow.  I love how on Google search results page you can navigate search results by using up and down arrow. If you haven’t tried it then give it a try on Google.com.  (There are plenty of examples on this on StackOverflow. However, I have tweaked to make it work for my example.)

We are going to modify our products page so that we can select an individual product using keyboard up/down arrow. After you select a product and hit enter (or return key) it should open up a details page for this particular product. To make this happen we have to do few things.
  1. We want to make products name as hyperlinks to details page so when you click on it, it should show us details page of that particular product. 
  2. Add a details view to show product details 
  3. Wire up the above two with a function in productscontroller.vb page 
  4. Use jQuery to make this thing happen. 
  5. Add Css to indicate which row is highlighted. 
In the Index.vbhtml change the first name as following: Add the following function in our ProductsController.vb

Right click the Details or anywhere in the function above and add another view with following details.

 Run the project and navigate to the following URL.

 Click on the first link and you will see details of it.


Now we have to add this simple javascript to this page.

@section scripts
     <script type="text/javascript">
    $(document).ready(function () {
        var $window = $(window);
        var current_index = -1;
        var $links = $("#plist").find(".detlink");
        var $rows = $("#plist").find(".prow");
        items_total = $links.length;
        //alert($links.length.toString());

        $window.bind('keyup', function (e) {
            if (e.keyCode == 40) {
                dehighlight_row();
                if (current_index + 1 < items_total) {
                    current_index++;
                    highlight_row();
                }
            } else if (e.keyCode == 38) {
                dehighlight_row();
                if (current_index > 0) {
                    current_index--;
                    highlight_row();
                }
            }
           
        });
       
        function highlight_row()
        {
            $rows.removeClass('prow');
            $rows.eq(current_index).addClass('prow-sel');
            //$input.val(current_index);
            $links.eq(current_index).focus();
        }
        function dehighlight_row() {
            $rows.removeClass('prow-sel');
            $rows.eq(current_index).addClass('prow');
            //$input.val(current_index);
            $links.eq(current_index).focus();
        }
    });
</script>
End Section


 From now onward if you want to add scripts to your individual view you should add them in a section as highlighted in yellow in the above code. This will render this tag at the bottom of you rendered page which is a recommended practice and improves performance. And this will load after the jquery scripts have loaded. If you don’t put your javascript script tag inside @section block then a Jscript runtime error will come up if you are debugging using Internet Explorer. If you are debugging using Chrome or Firefox it won't show you a dialog box with this error.

Microsoft JScript runtime error: '$' is undefined 

The above javascript code finds an element with “plist” which is our table and finds all the rows with “prow” class and puts in a $rows variable. Same thing we do will all the links with class “detlink” and put them in $links variable. And from there we just detect up and down arrow by checking the e.keyCode number and highlight and unhighlight that particular row. Once we find a particular row then we will focus that link by using .focus() function of jquery. $links.eq(current_index).focus();

Before finishing do this
1. Add id=”plist” to our table tag.
2. Add class="prow" to tag after for each loop
3. Add following classes to your site.css

.prow{}
.prow-sel {
    border:1px solid green;
}

Add a link to our navigation bar into our _layout.vbhtml page.

<nav>
                        <ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                            <li>@Html.ActionLink("Products", "Index", "Products")</li>
                        </ul>
</nav>

Run the project and click on the products page and navigate using up down arrow and then enter to show the details page for the selected product. 

Give your feedback or if you find any bugs or have a better way of doing it, I would be more than happy to know about it.  Thanks.