Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Sunday, May 12, 2024

.Net 8 MVC

.Net Model View Controller (MVC) is a Server Side Web Application Technology. It Comprises of Model, which is the object oriented representation of data by way of POCO classes. View represents the user interface. Controller represents the user Interaction. There are other alternatives like Razor Pages for creating Server Side .Net applications. Mastering MVC will go a long way in learning other technologies like .Net Web API(with Controllers).

.Net MVC application can be developed either using Visual Studio, Visual Studio Code C# Dev Kit or .Net CLI. I am going develop MVC using Visual Studio.

Convention Over Configuration

Convention over Configuration is a software design pattern which denotes following certain conventions to avoid a lot of configurations. MVC used Convention Over Configuration when it comes to Controllers and Views. Controllers All Controllers should be inside the controllers folder. Controllers should have a Controller suffix. HomeController - Controller name is actually Home. View All the views should be inside the Views folder. There will be a folder in the Views folder corresponding the the Controller. Eg: There will be a Home folder inside the Views Folder for holding the views corresponding to Home Controllers action Methods.

MVC Project Structure

Controllers

User Interaction happens through Controllers. Controllers comprises of Action Methods.
 using Microsoft.AspNetCore.Mvc;  
 namespace MVCShalvin.Controllers  
 {  
   public class HomeController : Controller  
   {  
     public IActionResult Index()  
     {  
       return View();  
     }  
     public IActionResult Privacy()  
     {  
       return View();  
     }     
   }  
 }  
Here there are Index and Privacy Action Methods which returns View.

View

MVC View are created using Razor syntax. Razor comprises of C# code and HTML templates. Razor files have .cshtml extension Inside the Views Folder there is a Shared folder which contains Layout.cshtml which contains the common look and feel for the pages like Header, Footer etc. @RenderBody() section within the Layout.cshtml contains the View specific UI.

Models

 namespace MVCShalvin.Models  
 {  
   public class Faculty  
   {  
     public string Name { get; set; }  
     public string Specialization { get; set; }  
   }  
 }  

Passing data from Controller to View

 using Microsoft.AspNetCore.Mvc;  
 using MVCShalvin.Models;  
 namespace MVCShalvin.Controllers  
 {  
   public class HomeController : Controller  
   {  
     Faculty faculty = new Faculty  
     {  
       Name = "Shalvin P D",  
       Specialization = ".Net"  
     };  
     public IActionResult Index()  
     {  
       return View(faculty);  
     }  
   }  
 }  
Here the faculty object is passed as a parameter to View.

Index.cshtml

 @model MVCShalvin.Models.Faculty  
 <div>Hello @Model.Name specializing in @Model.Specialization</div>  

Tuesday, October 20, 2015

AngularJS for .Net Developers Part 1

AngularJS is a popular client side MVC and MVVM Javascript library used for creating Single Page Application.

Starting an Empty Web Site Project in Visual Studio 2015 and adding Nuget packages for AngularJS Core and Routing.


Though AngularJs can be developed using any Text Editor I prefer using Visual Studio which also provides intellisense for AngularJS.


<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.js"></script>
</head>
<body>

    <div ng-app="">
        Name <input type="text" ng-model="Name"/>
        <br/>
        Hello {{Name}}
    </div>

</body>
</html>



AngularJS comprises of Directives which can be defined as  Html Atrributes. ng-model here behind the scene creates a property in the ViewModel. 
{{}} is equivalent to <% %> in Asp .Net Web Forms.

As you type inside the textbox, the Hello message gets updated,


ng-repeat Directive
ng-repeat is equivalent to foreach in C#, ie. iterating a colleciton.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.js"></script>
</head>
<body>
    <div ng-app="" ng-init="names=['Shalvin P D','Ajay','Rajeev']">
        <ul>
            <li ng-repeat="x in names">
                {{ x }}
            </li>
        </ul>
    </div>
</body>
</html>


Here I am using ng-init for initilizing the data.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.js"></script>
</head>
<body>
    <div ng-app="" ng-init="names=[
{name:'Shalvin',location:'Kochi'},
{name:'Rajeev',location:'Kollam'},
{name:'Ajesh',location:'Alappey'}]">

        <ul>
            <li ng-repeat="x in names">
                {{ x.name + ' - ' + x.location }}
            </li>
        </ul>
    </div>
</body>
</html>




Here I am using a complex array comprising of name and location.



$scope Service

In AngularJS whatever starts with $ is  a service. $scope service is equivalent to ViewBag in Asp .Net MVC. It is the glue between Controller and View. $scope supports two way data binding.

Modules
Modules are equivalent to namespace in .Net.






<!doctype html>

<html ng-app="Contacts">
<head>
    <title>Contact Management</title>
   
    <script src="Scripts/angular.js"></script>
    
    <script>
      
      var parking = angular.module("Contacts", []);
     
      parking.controller("HomeCtrl", function ($scope) {
       
        $scope.Contacts = [
          {Name: 'Shalvin'},
          {Name: 'Sooraj'},
          {Name: 'Mahesh'}
        ];
        
      });
    </script>
</head>

<body ng-controller="HomeCtrl">
    <h3>Modules and Controllers - Shalvin</h3>
    <table>
        <thead>
            <tr>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
               <tr ng-repeat="n in Contacts">
                   <td>{{n.Name}}</td>
            </tr>
        </tbody>
    </table>
 </body>
</html>



Here I am defining a Module named Contacts which contains a controller named HomeCtrl. Inside the controller I an array of Names and passing it to View.



Friday, April 30, 2010

Asp .Net MVC 2 with Visual Studio 2010 or Visual Web Developer 2010

Pro ASP.NET MVC 3 Framework, Third EditionAsp .net Mvc is the Web Development framework from Microsoft based on
the MVC architecture.

Asp .Net MVC is getting installed as a part of Visual Studio 2010 and
Visual Web Developer 2010.

Asp .Net 2 MVC Empty Web Application Project

Asp .Net MVC 2 Web Application comes with predefined
Membership and other frills which makes it easy
to get a head start, but abstracts away the inner working of MVC.

But I am taking another route. There is another
Asp .Net MVC 2 Empty Web Application Project.

Asp .Net MVC






















Lets start with Controllers. Controllers are responsible for handling
incoming request. It's a class that inherits from System.Web.Mvc.Controller.























I am naming the controller HomeController.

















I am replacing the existing code of HomeController which expects a View (which will be explained late) with a function that returns a string.
























If you run the application you will see a web page with the value of function.





















Views


Now Let's turn our attention to Views. A view is typically what you see in an Asp .Net MVC Application.

Preferably start a new new Asp .Net MVC 2 Empty Web Application so that we can start afresh.


The following diagram shows the default code within the HomeController class.































If you run the application you will receive a detailed error message stating that the view is missing.

































So right click the Index method and select Add View.



















Make sure you check off the Select MasterPage option because we haven't introduced Master Pages.
A view template called Index.aspx will created for you under ~/Views/Home/ directory.

Which comprises of plain HTML.





































Now if you run the application you will receive a blank form.


Lets replace the existing code with the code below. The code will return a
ViewData structure



public ViewResult Index()
{
ViewData["Blog"] = "ShalvinPD.blogspot.com";
return View();
}



Now lets show the ViewData in the View.
















Asp .Net MVC Views


Easiest way to develop Asp .Net MVC views are by using Html Helpers.


Name <%: Html.TextBox("Name") %>

<br />
<%: Html.CheckBox(".Net", true) %>.Net

<br />
<%: Html.RadioButton("Male", true) %>Male
<br />
<%: Html.RadioButton("Female", false) %>Female
<div>
Password <%: Html.Password("myPassword")%>
</div>
<div>
Address <%: Html.TextArea("Address", "Shalvin P D", 5, 20, null)%>
</div>

Kmug<%: Html.DropDownList("Kmug", new SelectList(new[] { "Shalvin", "Mathew" }), "Shalvin") %>

<br />
Technologies<%: Html.ListBox("myList", new SelectList(new[] { "Asp .Net", "Asp .Net Mvc" }), "Shalvin") %>

Tuesday, June 10, 2008

.Net C# Multi Tier Application

The 3-Tier architecture has the following three tiers:

Data Tier
This tier consists of Database Servers. Here information is stored and retrieved. This tier keeps data neutral and independent from application servers or business logic. Giving data its own tier also improves scalability and performance.
Application Tier (Business Logic/Logic Tier)
The logic tier is pulled out from the presentation tier and, as its own layer, it controls an application’s functionality by performing detailed processing.
Presentation Tier
This is the topmost level of the application. The presentation tier displays information related to such services as browsing merchandise, purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the browser/client tier and all other tiers in the network.
Lets take up creating a very simple multi tier application.

First we will see the Data Tier. Here I am using Sql Server 2005 as data store.



















Now we will create the Application Tier or the Business Tier. For this I am creating a Class Library Project.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace ShalvinBusinessObject
{
public class BusinessObject
{
public DataTable GetCategories()
{
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=ShalvinPDBlog;Data Source=.\sqlexpress");
cnn.Open();
da = new SqlDataAdapter("spAllCategories", cnn);
da.Fill(ds, "Cat");
return ds.Tables["Cat"];
}
}

Goto Build, Build Solution for building the dll.

Creating the User Tier

Start a Windows Application Project.
Go to project, Add Reference, Select Browse and Navigate to the bin, release folder of the previously creating class library project. Select the dll.

Now you can access the dll from your project.



















using ShalvinBusinessObject;


BusinessObject bo;
private void Form1_Load(object sender, EventArgs e)
{
bo = new BusinessObject();
dataGridView1.DataSource = bo.GetCategories();
}

Here I am creating an Object of the Class in the previous dll and binding an dataGridView to the GetCategories method.

Monday, January 7, 2008

.Net Multi-Tier Application

This blog takes up the issue of creating multi tier application with VB.Net (Windows Forms) and C# (Asp .Net).

Start up with creating two stored procedures.

create procedure spAllCategories
as
select * from Categories
go


create procedure spInsertCategories (@pCategoryName varchar(40), @pDescription varchar(60))
as
insert into Categories values (@pCategoryName, @pDescription)
go

Create an new class Library project called ShalvinLib and add two methods that will call the stored procedures. This is going to act as the business tier.

Imports System.Data.SqlClient
Public Class BusinessLayer
Public Shared Function GetCategories() As DataTable
Dim cnn As New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind;Data Source=.\sqlexpress")
cnn.Open()

Dim ds As New DataSet
Dim da As New SqlDataAdapter("spAllCategories", cnn)
da.Fill(ds, "Cat")
Return ds.Tables("Cat")
End Function

Public Shared Sub InsertCategories(ByVal mCategoryName As String, ByVal mDescription As String)
Dim cnn As New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind;Data Source=.\sqlexpress")
cnn.Open()
Dim cmd As SqlCommand

cmd = New SqlCommand("spInsertCategories " + mCategoryName + ", " + mDescription, cnn)

cmd.ExecuteNonQuery()

End Sub

End Class

C# and Asp.Net
Here instead of using Windows Forms I am opening a Asp.Net Application and Instead of starting a new class Library I am adding a Class to the existing project.

web.config




using System.Data.SqlClient;
public static DataTable GetCategories()
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
SqlDataAdapter da = new SqlDataAdapter("spAllCategories", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "Cat");
return ds.Tables["Cat"];
}

public static void InsertCategories(string mCategoryName, string mDescription)
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
cnn.Open();
string strSql = "spInsertCategory '" + mCategoryName + "', '" + mDescription + "'";
SqlCommand cmd = new SqlCommand(strSql , cnn);
cmd.ExecuteNonQuery();
}


Having created the class library dll, we can proceed to create a windows forms application.
Set a reference to the class library. Create the visual interface and invoke the methods of class library.

Dim bl As New ShalvinLib.BusinessLayer
Private Sub frmShowCategories_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.DataSource = bl.GetCategories
End Sub

C# and Asp .Net
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = BusinessLayer.GetCategories();
DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
BusinessLayer.InsertCategories("Books", ".Net Books");
Response.Write("Record Saved");
}

Happy programming