ASP .NET MVC3

http://goo.gl/Yh1HH
http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/accessing-your-model's-data-from-a-controller
https://skydrive.live.com/view.aspx?cid=8FB6C8BD5D453222&resid=8FB6C8BD5D453222%21906&app=PowerPoint


MVC stands for model-view-controller. MVC is a pattern for developing applications that are well architected and easy to maintain. MVC-based applications contain:
  • Controllers: Classes that handle incoming requests to the application, retrieve model data, and then specify view templates that return a response to the client.
  • Models: Classes that represent the data of the application and that use validation logic to enforce business rules for that data.
  • Views: Template files that your application uses to dynamically generate HTML responses.


public class Movie {
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}
public class MovieDBContext : DbContext {
    public DbSet<Movie> Movies { get; set; } }
<add name="MovieDBContext" 
         connectionString="Data Source=|DataDirectory|Movies.sdf" 
         providerName="System.Data.SqlServerCe.4.0"/>
//Método Edit modificado para que retorne página no encontrada al cargar un id incorrecto
public ActionResult Edit(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}
//Médotodo de Búsqueda agregado en el Controlador
public ActionResult SearchIndex(string searchString)
{          
    var movies = from m in db.Movies
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    return View(movies);
}

Displaying the SearchIndex Form

public ActionResult SearchIndex(string searchString)
{          
    var movies = from m in db.Movies
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    return View(movies);
}
Después del create en la vista del search index

@using (Html.BeginForm()){   
         <p> Title: @Html.TextBox("SearchString") 
         <input type="submit" value="Filter" /></p>
        }

Adding Search by Genre

public ActionResult SearchIndex(string movieGenre, string searchString)
{
    var GenreLst = new List<string>();

    var GenreQry = from d in db.Movies
                   orderby d.Genre
                   select d.Genre;
    GenreLst.AddRange(GenreQry.Distinct());
    ViewBag.movieGenre = new SelectList(GenreLst);

    var movies = from m in db.Movies
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    if (string.IsNullOrEmpty(movieGenre))
        return View(movies);
    else
    {
        return View(movies.Where(x => x.Genre == movieGenre));
    }
}

Adding Markup to the SearchIndex View to Support Search by Genre

 Views\Movies\SearchIndex.cshtml 
<p>
    @Html.ActionLink("Create New", "Create")
    @using (Html.BeginForm()){   
         <p>Genre: @Html.DropDownList("movieGenre", "All")  
           Title: @Html.TextBox("SearchString")  
         <input type="submit" value="Filter" /></p>
        }</p>
The Global.asax file contains the class that defines the entire application for the project, and contains an  Application_Start event handler that runs when the application first starts.


using System.Data.Entity;            // Database.SetInitialize
using MvcMovie.Models;              // MovieInitializer


protected void Application_Start()
{
    Database.SetInitializer<MovieDBContext>(new MovieInitializer());

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}


Introduction to LINQ Queries (C#)

query is an expression that retrieves data from a data source. Queries are usually expressed in a specialized query language. Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML. Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.

All LINQ query operations consist of three distinct actions:
  1. Obtain the data source.
  2. Create the query.
  3. Execute the query.
The following example shows how the three parts of a query operation are expressed in source code. The example uses an integer array as a data source for convenience; however, the same concepts apply to other data sources also. This example is referred to throughout the rest of this topic.
class IntroToLINQ
{        
    static void Main()
    {
        // The Three Parts of a LINQ Query: 
        //  1. Data source. 
        int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation. 
        // numQuery is an IEnumerable<int> 
        var numQuery =
            from num in numbers
            where (num % 2) == 0
            select num;

        // 3. Query execution. 
        foreach (int num in numQuery)
        {
            Console.Write("{0,1} ", num);
        }
    }
}
The following illustration shows the complete query operation. In LINQ the execution of the query is distinct from the query itself; in other words you have not retrieved any data just by creating a query variable.
Complete LINQ Query Operation

VALIDACIÓN AL MODELO

core design tenets of ASP.NET MVC is DRY ("Don't Repeat Yourself").
EN EL MODELO (TI.CS)
using System.ComponentModel.DataAnnotations;

public class Movie
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Title is required")]
    public string Title { get; set; }

    [Required(ErrorMessage = "Date is required")]
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime ReleaseDate { get; set; }

    [Required(ErrorMessage = "Genre must be specified")]
    public string Genre { get; set; }

    [Required(ErrorMessage = "Price Required")]
    [Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
    [DisplayFormat(DataFormatString = "{0:c}")]
    public decimal Price { get; set; }

    [StringLength(5)]
    public string Rating { get; set; }
}
Modificar el metodo Details
public ActionResult Details(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}
Modificar el método Delete

 // GET: /Movies/Delete/5
public ActionResult Delete(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}
//
// POST: /Movies/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    db.Movies.Remove(movie);
    db.SaveChanges();
    return RedirectToAction("Index");
}

 var url = '<%=Url.Action("Accion", "Controlador",new{perspectivaID="param-1",tipoCOD="param-2"})%>';
                url = url.replace("param-1", perspectivaID);
                url = url.replace("param-2", tipoCOD);
                $.post(url, null, function (data) {
debugger
//retorna listado y colocar en grid

});












No hay comentarios:

Publicar un comentario