Quantcast hello world : mvc web application part 1

hello world : mvc web application part 1

by Neon Quach 4. June 2010 03:32

MVC (Model - View - Controller) là 1 trong những mẫu kiến trúc nổi tiếng nhất hiện nay, mà trước đây vào năm 1979 chúng ta đã được biết với tên là Thing - Model - View - Editor, nay là MVC.

Mô hình MVC phân chia ứng dụng ra làm ba phần, mà trước đây chúng ta đã quá quen với mô hình 3 lớp:

Model: tập hợp các lớp mô tả dữ liệu, đảm nhận tốt việc xữ lý rule (bussiness rule) cho việc thay đổi và chỉnh sửa dữ liệu.
View: giao diện người dùng.
Controller: là tập hợp các lớp chịu trách nhiệm xử lý các giao tiếp của người dùng .

Trong bài blog này mình sẽ hướng dẫn mọi người viết 1 chương trình HelloWorld để làm quen với MVC sử dụng visual studio 2010 built in mvc 2.0.



Sau khi tạo 1 mvc web application, 1 hộp thoại xác nhận việc tạo test cho ứng dụng hay không, để tiếp tục chúng ta chọn no, don't create a unit test project



Sau khi click OK, ứng dụng mvc sẻ có cấu trúc như sau:


Content: các file static chẳng hạn như: css và image
Controller: các lớp controller
Model: các model của ứng dụng
Scripts: các file javascrip
Views: các trang aspx


Để bắt đầu với ứng dụng mvc HelloWorld, chúng ta click chuột phải vào thư mục Controllers chọn Add Controller (Ctrl M + Ctrl C)

using System.Web.Mvc;

 

namespace HelloWorld.Controllers

{

    public class HelloWorldController : Controller

    {

        //

        // GET: /HelloWorld/

        public ActionResult Index()

        {

            ViewData["hello"] = "http://code2code hello world";

            return View();

        }

    }

}

Bước tiếp theo là click chuột phải vào HelloWorldController chọn add View (Ctrl M + Ctrl V).

Đoạn code sau sẻ lấy giá trị từ ViewData từ Controller gửi lên

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

    Index

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>

        <%= ViewData["hello"]%></h2>

</asp:Content>


Giờ nhấn F5 http://localhost:13541/HelloWorld chúng ta sẽ thấy 1 dòng HelloWorld được in ra.

Tags:


Categories: mvc

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers