Day #2: Learn ASP.NET MVC 5- Adding View

Day #1: Learn ASP.NET MVC 5- Adding Controller

On Day1 we learnt about Adding Controller. Today we will learn to add View in MVC project. Let us start with understanding with is View?

View is part of MVC that renders user interface. View contains markup that gets render with ViewEngines. ViewEngines generates View in ASP.NET MVC framework. There are two kinds of View Engines. One is aspx engine and other Razor engine.

We can say View is User Interface in MVC application and it never talks to database or model directly. It does not contain any business or application logic. Controller returns a View to be rendered.

image

You can add a View, right click on Product subfolder and select Add from context menu and then select template MVC 5 View Page with Layout.

image

There are four options for Views.

  1. MVC 5 View Page
  2. MVC 5 View Page with Layout
  3. MVC 5 Layout Page
  4. MVC5 Partial Page

Let us start with adding a MVC5 View Page with Layout. Give name of the View as of the action name. For example, if we have action in controller as below,


  public ActionResult Index()
        {
            return View();
        }

Then we will create a View with name Index since action name is Index and it is returning view. Next we need to select layout page. Let us go ahead and select a Layout.cshtml from Shared folder.

image

After adding View, you will find that inside Views->Product folder index.cshtml being added.

image

By default following code gets created in Index view

image

Let us explore above code line by line,

  • We are setting layout of view as _Layout.cshtml from Shared folder.
  • ViewBag is used to pass parameters. We are setting Title of the View as Index.
  • On DOM creating some HTML elements like <h2> and <p>

Now let us go ahead and run application. On navigating Index action in Product controller, you will get index view rendered in browser.

image

Let us go ahead and explore _Layout.cshtml. We are passing title from View to layout using ViewBag.

image

On running application, you may notice that browser title is set to Index-My ASP.NET Application. On further exploring _Layout.cshtml, you will find navigation links and footer. If required you can change content of layout as well.

Next let us see how we can pass data from Controller to a View. Before we go into demo section, let us understand that View will never interact with Model directly and perform any business logic. Controller will talk to Model and perform business operation on data and then pass that to View to get rendered.

image

Some of the important points are as follows,

  1. View never perform business logic
  2. View never interacts with Model
  3. Controller talk to Model , performs business logic and pass data to View

So let us say we want to pass data from Controller to View. Controller got an Action named Data as below,


    public ActionResult Data(string fruit, int eatingtimes)
        {
            ViewBag.fruit = fruit;
            ViewBag.times = eatingtimes;
            return View();

        }

From Data action, we are passing fruit and times as parameter from Controller to View. We are using ViewBag property to pass data from Controller to View. Now these passed data can be used on View as below. We have created a View named data without any layout.


 <div>
        <h2>Data</h2>
        <ul>
            @for (int i = 0; i < ViewBag.times; i++)
            {
                <li>@ViewBag.fruit</li>
            }
        </ul>

    </div>

In Route we have added a new Route as below,


  routes.MapRoute(
               name: "Product",
               url: "{controller}/{action}/{fruit}/{eatingtimes}"
           );

Let us go ahead and run application. We are passing mango as fruit and 9 as eatingtimes. As a output Mango will get render 9 times on View.

image

This is the way you can pass parameters from Controller to View. In further posts, we will complexity around Views and working with different kind of Views. I hope you find this post useful. Thanks for reading.

About these ads

Day #1: Learn ASP.NET MVC 5- Adding Controller

 

After long time, I am back to web development. At current web development paradigm, ASP.NET MVC framework is one of the most popular and heavily used web development framework. Seeing popularity and usefulness of ASP.NET MVC, I have decided to write easy to go blog series on this. In this blog post series, each day I will share my learning in form of blog posts.

In day 1, let us learn about Controller. Very first in simpler words,

“Controller does all the actions in MVC. It handles user interactions or inputs. It passes users’ data to Model and selects a View to render on UI”

image

In more coding terms, Controller can be define as below,

  1. Controller is a class
  2. It contains one or more methods called Actions
  3. An Action can return simple string or a selected View to UI
  4. Action takes all browser requests or user inputs
  5. It retrieves data from Model
  6. It selects View to be rendered on UI

You can add a controller by right clicking on Controllers folder in solution explorer. In context menu select Add->Controller. There are different types of Controller templates are available to add. Let us go ahead and select MVC 5 Controller- Empty template to add controller.

image

Next give name to Controller. I am giving name as ProductController.

image

In solution explorer, you will notice In Controller folder, ProductController.cs file being added and in Views folder, there is subfolder Product being added.

image

Next let us go ahead and remove default code created and following two actions. First Action is Index (It is default) action. Index action does not take any input parameter. Second Action added is Welcome. It takes two input parameters id and name.

 


public class ProductController : Controller
{
//
// GET: /Product/
public string Index()
{
return "this is default action";
}

public string Welcome(string name, int id)
{
return "this is welcome action" + name + "with id " + id;
}
}

Following points are worth noticing about ProductController.

  1. ProductController class extends Controller class
  2. Actions are created as methods.
  3. In this case Actions are returning string.
  4. Actions can return other types as well. We will discuss them in further posts.
  5. Actions can take zero or more input parameter.

Let us go ahead and run application. Default action of Product controller is index. On navigating Product Controller, Index action will be called. In this case Index action is returning a string.

clip_image002

We have put one more action Welcome in Product controller. This takes two input parameters Id and name. You can call Welcome action as below. We are passing two input parameters as query string.

image

Better approach to pass input parameters are as Route Data than query string. Id is default input parameter. So instead of passing id as query string, you can pass it as route data as well.

clip_image002[6]

You can find default route and parameters in RouteConfig.cs.

 

clip_image003

 

In above code as you see default controller is Home, default action is Index and default optional parameter is id. If you want to pass other input parameters as route option, you can very much do that by adding more routes.

clip_image005

We have added a route with name and id as parameter. On running application, now you can pass name and id as route option.

clip_image007

This is the basic of working with Controllers in MVC. In further posts we will get into deeper concepts of Controllers. I hope you find this post useful. Thanks for reading.

ASP.Net Web API Service in Windows Phone: Part 4 of Many

Creating First HTTP Service using ASP.NET Web API: Part1 of Many

Consuming ASP.NET Web API Service using HttpClient: Part2 of Many

How to Self-Host ASP.Net Web API: Part 3 of Many

In this post we will consume ASP.Net Web API HTTP Service in Windows Phone Application. If you do not specify header information in HTTP request then by default ASP.Net Web API service returns JSON data. So essentially there are three steps involved in consuming HTTP Service from ASP.Net Web API in Windows Phone Application.

  1. Make a HTTP Request
  2. Read data from HTTP Response
  3. Parse returned JSON data and bind data to data bound control

In this post we are going to consume service created in this POST

I have created a Windows Phone Application by choosing target framework 7.1. We are going to display Bloggers Data returned from ASP.Net Web API service in a ListView. Essentially we are going to consume a JSON Data from a HTTP Service. For that add below references in the project.

image

We are going to de-serialize JSON data using DataContractJsonSerializer class. We need to create a class at client side representing Bloggers entity from the service. Let us create a class called BloggersClient. We will de-serialize JSON data returning from the HTTP service in this object of this class.


namespace WindowsPhoneClient
{
public class BloggersClient
{
public string Id { get; set; }
public string Name { get; set; }
public string AreaOfIntrest { get; set; }

}
}

Once the client class is in placed add following references,

image

We are going to download JSON data from ASP.Net Web API service using WebClient class. Make sure that you are passing URL of your HTTP Service.

image

In the completed event, we will parse returned JSON using DataContractJsonSerializer class. In following code,

  • Creating MemoryStream form returned result
  • Creating object to de-serialize the returned JSON data
  • Reading de-serialized data object in List of BloggersClient
  • Setting List of BloggerClient as ItemSource of ListBox. On the XAML we have put a ListBox with name lstBloggers.

image

Code behind to load data from ASP.Net Web API HTTP Service on page load of the application and s display in ListBox is as following


using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace WindowsPhoneClient
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:39192/api/Bloggers"));
}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream s = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<BloggersClient>));
List<BloggersClient> result = (List<BloggersClient>) ser.ReadObject(s);
lstBloggers.ItemsSource = result;
}
}
}

On the XAML, we have put ListBox control do bind data from HTTP Service in the control.

If you are not aware of Data Binding in ListBox then watch a quick Video here


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="ASP.Net Web API" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="lstBloggers">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
<TextBlock Text="{Binding AreaOfIntrest}" Style="{StaticResource PhoneTextAccentStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>

Now press F5 to run the application. You should able to get Bloggers detail from ASP.Net Web API service in Windows Phone Application.

image

I hope you find this post useful. Thanks for reading.