Saltar apartados

views

Creating a sight to the controller

Already we have seen the first element of the group MVC. Now it is the moment to learn to use sights.

For this we created a new controller that will call sesion1Controller. To add a sight, situated us on the definition of any of the methods (by defect create Index) and pressed the right button. The first option allows us create a sight for the method.

Creando una vista para un método del controlador

It Will appear a window with the name of the equal sight to the one of the method. Desmarcamos The section of main page (Master page), although the normal are to work with main pages, and pressed Add.

Ventana de opciones para definir la nueva vista

It appears us a new window that remembers us a lot to the ASP.NET Traditional with our window to be able to edit our code HTML. We add something of code to see that can integrate code .NET.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

Index

<%= "Sight called by the controller Sesion1" %>

It has generated us in the folder Views, a new folder Sesion1 (name of the controller) and inside this the file Index.aspx (The method).

Ubicación de las vistas dentro del un proyecto ASP.NET MVC

We generate the solution and access with the browser to http://localhost:52314/Sesion1/.

Visualización de la vista en el navegador

Step of information of the controller in sight

The simplest form to happen information of the controller in sight is by means of the collection ViewData.

We assign some value in the controller

namespace MvcUA.Controllers

{

public class Sesion1Controller : Controller

{

//

// GET: /Sesion1/

public ActionResult Index()

{

ViewData["Course"] = "Course of ASP.NET MVC 2";

return View();

}

}

}

And can recover it from the sight

<%= "The name of the course is: " + ViewData["course"] %>

The result in the browser

Pasar datos desde el controlador a la vista

We can happen no only variable, but smart of values. We go to send the listing of students

namespace MvcUA.Controllers

{

public class Sesion1Controller : Controller

{

//

// GET: /Sesion1/

public ActionResult Index()

{

List Students = new List { "Antonio", "Juan", "Luis" };

ViewData["Course"] = "Course of ASP.NET MVC 2";

ViewData["Students"] = students;

return View();

}

}

}

In the sight recover it and showed them

<%= "The name of the course is: " + ViewData["course"] %>

<%

Response.Write("
Listing of students");

foreach (string Student in (List)ViewData["students"])

{

Response.Write("
" + Student);

}

%>

Computing service ASP.NET MVC 2 Framework


Universidad de Alicante
Carretera de San Vicente del Raspeig s/n
03690 San Vicente del Raspeig
Alicante (Spain)

Tel: (+34) 96 590 3400

Fax: (+34) 96 590 3464

For further information: informacio@ua.es, and for enquiries on this web server: webmaster@ua.es

Carretera San Vicente del Raspeig s/n - 03690 San Vicente del Raspeig - Alicante - Tel. 96 590 3400 - Fax 96 590 3464