Friday, March 28, 2014

Moving data from one view to another view in MVC

Though there are many ways to handle this situation, I recently had to try the same and ended up using localStorage and it really helped to handle data at various levels of requirements.

Getting to use it is so easy and simple. Just make sure you have HTML5 for schema validation and rest is swift.

When setting up the value, this is what needs to be done :

<script>
   localStorage.setItem("firsttest", "Hello user...");
</script>

When retrieving the value, just do it as below..

<script>
  var testvalue =  localStorage.getItem("firsttest");
</script>

On a quick note, lets see what is localStorage.

   localStorage - These are nothing but Web Storages, replacing the need to use cookies. Web storages are faster and can accomodate up to 5MB of data. If you want to store / retrieve data based on sessions, then the above can be replaced to use sessionStorage instead of localStorage.

Happy coding....

Wednesday, March 19, 2014

How to implement an autocomplete within MVC

In this tutorial to implement AutoComplete, we will go over a simple way to implement. Before doing so, make sure you have references to jQuery. As a reference, I am giving my jQuery references below (as in _Layout.cshtml)



 In creating the UI, it is a very simple design. More concentration would go on the script that ties up data with the text box. Just for the tutorial, I am creating a view named AutoCompleteTest.cshtml

  In our first step, will create a text box and assign an id value, to be referenced further.

   

   Now, will concentrate on getting the autocomplete assigned to this text box, by invoking ajax call to a controller method, which in turn would return a type of List<string> with dynamically generated values as data source for our example.

 Below is the script that we will be using to invoke it. Will go one by one on why and how it is used.


 To initiate autocomplete, we would use jQuery to get the id of textbox and invoke its autocomplete method as $("#txtautocomplete").autocomplete();

If we have an array declared, we can still assign that data as a source or we can write a function as above to invoke ajax call (better with MVC approach) and display the data on its successful get.

Here we declare the datatype is json, since our controller will be returning only json data. Parameter to our controller will be sent via the data option.  Everything else, is a regular definition of an ajax call.

Here, I had defined minLength:1, which indicates, as soon as I start typing, I prefer the autocomplete to start working (hitting my controller method to return matching data). Also for open function, I am trying to set the z-index value to be 1000. This is just to be safe and make sure our autocomplete drop down doesn't be hidden when typing values (more possibility that others with greater z-index might overlap).

  Now that we have everything setup in the UI, lets go create a controller method to return data in json format.

I had written this initial code, just to load the view without doing any thing. Now, will write a method to return data based on the parameter passed.

In this method, I am creating a list type of List<string> and load it with data, by looping through and adding it to them.

Once I have the data ready, I would filter it based on the parameter passed, which is searchtext here and return the filtered list as json result set, back to my view.  Now, we have set up everything that is required to implement autocomplete in MVC. When we run and test it, you should see something like this....






Happy coding....

Wednesday, March 12, 2014

HTML 5 tutorial - How to access web service (Web API) from HTML file



In this tutorial, we will go over, how to retrieve data using ajax and display it within our HTML page.

To start with, will create a new ASP.NET empty web application and keep adding files as and when we need to do.

Select New project option from the menu and select the following option :



Once you do that, the solution explorer should be loaded with your empty file structure.



Now lets add a HTML file and call it HTML_API.  The most important task for me to achieve in this HTML will be to invoke a web service using ajax call and display the results within a table structure.


Once the files is created, lets edit the HTML and make necessary changes to make ajax calls. To achieve this, we need to include jQuery within our script tag. This can be achieved in more than one way.


  1. You could either download the file here and include it in your project
  2. You could use any of the CDN's below and refer them online.

 CDN's are nothing but Content Delivery Network. The purpose of CDN is, they host the required files and by referring them, you can still achieve the same output.

Below is a sample of various CDN options (excludes including through physical path).

In our tutorial, I will be using google api's to refer for jQuery. More over, I will be using the same Web API tutorial (which I used for MVC Grid) to display data. 

Below is the ajax code to invoke Web Service from HTML 5 page.

What is being done here is, invoking the web service and on its successful return with data, we are creating a table row and inserting the values within <td> tags. The whole content is finally appended to the table with id "category" and that would complete the getting results displayed within the table tag.

Below is the image for having the table tag as defined above.

Earlier while testing, I had this error occurring and unable to get the data from database. That's when I realized that I needed the following line.

jQuery.support.cors = true;

CORS are nothing but, Cross Origin Resource Sharing and mainly used for Cross-domain requests.

The final result is below:


Happy coding...

Friday, March 7, 2014

Path issues when deploying MVC applications



One of the issues that comes up when deploying MVC projects to server is, having a conflict with script path, images path,etc . The path structure that deployment does is, creating project name folder and beneath, there is folders for image,script, etc. Irrespective of how you had included in the project, this is the final structure that needs to be considered.

   To test the same, I deployed my project with the following structure working fine locally.  This image showed up with no issues, but it did not work after deployment.

<img src="../../Img/test1.jpg" />

  All I had to do is, replace the above with the following code and it works. :-)...

<img src="~/Img/test1.jpg" />

   Very simple, isn't it? This works fine locally and after deployment too... I had seen in many websites, where I was advised to use Url.Content, actually there was no need for me to implement it... every thing started working fine. Just in case, if this scenario doesn't work, you can always consider using Url.Content("~/<path for file>") and that might help you. Just a thought...

Happy coding...


Thursday, March 6, 2014

How to invoke a Web API method within a controller.....


ASP.Net Web API is a powerful tool to retrieve data and to serve a broad range of clients. Once created, it can used to access data in mobile applications too.

   Web API's are helpful to create RESTful services and are similar to MVC controllers, but here the class will be derived from APIController when compared to MVC applications where it will be just Controller. This framework is really helpful to build HTTP based services and can very well control the returned data type  to be json or xml.

   If you are developing an application in MVC, it well suites to have Web API, as it is also based on routing concepts.

 Now lets get into the tutorial to see how to invoke a method in Web API....

 In your MVC controller method, make sure you invoke HttpClient to get started. (for HttpClient, if you have any issues, make sure you refer the namesapce : System.Net.Http;)

 We will use HttpClient and define the URI property within client object as below.....  This defines our base url that the web service is located at...

string url = "http://localhost:1001";
 using (HttpClient client = new HttpClient())
{
     client.BaseAddress = new Uri(url);
     client.DefaultRequestHeaders.Accept.Add(new                  
                                             MediaTypeWithQualityHeaderValue("application/json"));
      
}

In the above, we are using Headers property to define, what kind of data will be handled from server. In the above scenario, we are letting it know that we are dealing json format data. (you can even prefer to use xml format, based on what fits your need well).

Before invoking the method, we should make sure the controller name and method name that we are about to call for data. This defines our path, that we will be using with our client object.

Example : below is our Web API definition...


Given the class name is WebApiTestController, this is how we will use it with our client object.

HttpResponseMessage msg = client.GetAsync("api/WebApiTest/<MethodName>").Result;

Using the above, we can identify if our call was successful by trying the method :
 if(msg.IsSuccessStatusCode), then we had successfully accessed our method  and we can retrieve our data as below...

var mylist = msg.Content.ReadAsAsync<object>().Result;

To have the list converted to a compatible IList<T> object, you can use Result.ToList(); The resultset would be a List object.

  Below is the compiled list for complete code to invoke a web API method....




Happy coding...



Wednesday, March 5, 2014

HTML Web Grid - How to filter the records using a text box.

In this tutorial, we will go over how to filter a web grid based on an input from a text box. Before getting started, I will be using my earlier tutorial on Web Grid. In that tutorial, I used web service to invoke data from Northwind to display category id, name description etc within a grid.

   Now I will use the same data to filter it based on user input. I will add a textbox and a search button on top of the grid, that will drive the data source to the web grid.

This is my existing screen.



Once I add the new UI elements in this view, this is how my new screen will be...


I had moved my grid to a separate partial view to ease the process of reloading data. I created a new view named "gridview.cshtml" and included the code as given below...


In this view, I had defined an attribute as id using htmlAttributes property. I will be referring this id to display the refreshed data after filtering from existing source.... (I am reusing styles for this grid from various other web sites). Once this is defined, we can start working on UI filter elements and button search click event to do the rest.

I will use a div tag to enclose filter search and the partial view for grid. Below is the code to implement them.


In the above code, I will be displaying the grid through @Html.Partial by passing in the partial view name as the parameter.  By isolating the view to be refreshed, it will help us to re-load it many times, without affecting the other parts of UI.

  Remaining part with the UI will be to write the search click event, before we get into the controller part of the code. Lets write the search event by making an ajax call to the controller method with the parameter value and do a filter on it.

In the above code, I am making a call to my controller method TestPage_Filter, which would fetch the data for web grid without filtering it (by doing it this way, you could use the same code while loading the page too avoiding redundant code). Whatever is entered into the text box will be retrieved for filtering and passed in through the data option. Here we are retrieving the search criteria and storing it in a variable called srchitem. Same will be passed on to the controller on click of the button. On successful completion of process,  the returned data is now loaded into the grid through the grid's id, using .html(result).

This being done, we are totally done with the view side of it. In controller, I had done the same steps for loading the initial grid data and storing it in an IEnumerable<CategoryData> variable. Once I have it there, I use linq to objects to filter my data based on the entered text. Below is the code to retrieve my grid list and filter it.

In the above code, txtval is the parameter passed to the controller method. Here I am doing a filter based on CategoryDescription field, similarly you can do the same for other fields too. Or even better, have a drop down selection in UI and get users response to know, based on which field criteria, it is being searched.

Once I have the filtered list, I will loop through my data model object to map it to my grid elements as below.


If you refer the code above, you can see that the view, I am returning is gridview (the one that contains the grid) along with the filtered data. This data will be associated with the grid and re-loaded. Final view after filtering should be like this....



Happy coding......


HTML Dropdown List

This tutorial will illustrate an example of, how HTML Dropdownlist can be used to load data and include an event to trigger and load another drop down based on the values from the first one.

Open a new MVC project and add a view to execute the following code. For tutorial purpose, I had created a new razor view as HtmlDD.cshtml

 Lets create a class that will be used for the selected values for both the drop downs.

Lets include the model that we will be using in this view.  We will be referring the properties declared within the model and associate them to the selected values in both the drop downs.

 In your view, add the following code for drop down.
In the above code, we included two drop downs. First one will be loaded with values, when loading the page. Second one will be empty, until the we select a value from the first drop down.

To load the first drop down, implement the code below (I am using json data and so I chose to handle it this way).

Until now, running this page should get you displaying with two drop downs (assuming you have an empty structure for htmlDDDemo method), with the first one loaded with values needed. Will go over the rest of code to review, how to implement on change event of first drop down, that will trigger the changes (adding items) to second drop down. This is just my scenario, but again, this can be used to display a Web Grid, filtered by the selected drop down value or other desired actions.




In the above javascript method htmlDDDemo, we are passing in paramvalue, which is the selection from the first drop down and I am passing the same to my controller/methodname?parameter=passedinvalue....

On execution of this script, my second drop down will be loaded with filtered data based on the parameter provided.

Happy coding....