Thứ Hai, 4 tháng 4, 2016

Note ASP.Net MVC

1.   Views\_ViewStart.cshtml
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
TheViews\_ViewStart.cshtml file defines the common layout that all views will use, therefore you can comment out or remove that code above
You can use the Layout property to set a different layout view, or set it to null so no layout file will be used.

2.   Controller – View
let's first talk about passing information from the controller to a view. Controller classes are invoked in response to an incoming URL request. A controller class is where you write the code that handles the incoming browser requests, retrieves data from a database, and ultimately decides what type of response to send back to the browser. View templates can then be used from a controller to generate and format an HTML response to the browser.
Controllers are responsible for providing whatever data or objects are required in order for a view template to render a response to the browser. A best practice: A view template should never perform business logic or interact with a database directly. Instead, a view template should work only with the data that's provided to it by the controller. Maintaining this "separation of concerns" helps keep your code clean, testable and more maintainable.

3.   Remove unused Using
Note: Several unused using statements have been removed. You can do this by right clicking in the file, click Organize Usings, and then click Remove Unused Usings.
Description: http://media-www-asp.azureedge.net/media/46638/remove.png
4.   Default DB of  Entity Framework
Entity Framework will default to using  LocalDB
LocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to  work with databases as .mdf files. Typically, LocalDB database files  are kept in the App_Data folder of a web project.

The name of the connection string must match the name of the DbContext class.
          name="MovieDBContext" 
                 connectionString="..." 
                 providerName="System.Data.SqlClient" /> 

using System;
using System.Data.Entity;
 
namespace MvcMovie.Models
{
    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; }
    }
}


The ValidateAntiForgeryToken attribute is used to prevent forgery of a request and is paired up with @Html.AntiForgeryToken() in the edit view file (Views\Movies\Edit.cshtml),
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
}

@model MvcMovie.Models.Movie
 
@{
    ViewBag.Title = "Edit";
}

Edit
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()    
    
class="form-horizontal">
        ...
    

6.   Bind
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}
The ASP.NET MVC model binder takes the posted form values and creates a Movie object that's passed as the movie parameter. The ModelState.IsValid method verifies that the data submitted in the form can be used to modify (edit or update) a Movie object.

7.   Html.BeginForm()
@using (Html.BeginForm("Index","Movies",FormMethod.Get))


8.   ViewBag & @Html.DropDownList
@Html.DropDownList("movieGenre", "All")
The parameter "movieGenre" provides the key for the DropDownList helper to find a  IEnumerable<SelectListItem> in the  ViewBag
    var GenreLst = new List();
 
    var GenreQry = from d in db.Movies
                   orderby d.Genre
                   select d.Genre;
 
    GenreLst.AddRange(GenreQry.Distinct());
    ViewBag.movieGenre = new SelectList(GenreLst);


9.   Add new field to model (Code first)
If the updated Movie model class in the application is now different than the schema of the Movie table of the existing database. (There's no Rating column in the database table.) 
There are a few approaches to resolving the error:
1.     Have the Entity Framework automatically drop and re-create the database based on the new model class schema. This approach is very convenient early in the development cycle when you are doing active development on a test database; it allows you to quickly evolve the model and database schema together. The downside, though, is that you lose existing data in the database — so you don't want to use this approach on a production database! Using an initializer to automatically seed a database with test data is often a productive way to develope an application. For more information on Entity Framework database initializers, see Tom Dykstra's fantastic ASP.NET MVC/Entity Framework tutorial.
2.     Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script.
3.     Use Code First Migrations to update the database schema. (Build -> add-migration Rating -> Build -> update-database)

10. [RegularExpression(@"^[A-Z]+[a-zA-Z'\s-]*$")]
In the code above, must use only  letters (white space, numbers and special characters are not allowed


11.  Install Entity Framework
From the Tools menu click NuGet Package Manager and then click Package Manager Console.
In the Package Manager Console window enter the following command:
Install-Package EntityFramework


12.   relationship between Student and Enrollment entities

Description: Class_diagram

    public class Student
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
 
    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }
        
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }
Entity properties that are named ID or classnameID are recognized as primary key properties.
A property is interpreted as a foreign key property if it's named  (for example,StudentID for the Student navigation property since the Student entity's primary key is ID). 

13.   Install the PagedList.MVC NuGet Package
In the Package Manager Console window, make sure ghe Package source is nuget.org and the Default project is ContosoUniversity, and then enter the following command:
Install-Package PagedList.Mvc

14.   interception  and Log SQL excute

15.   SQL Query in LinQ

string query = "SELECT * FROM Department WHERE DepartmentID = @p0";
Department department = await db.Departments.SqlQuery(query, id).SingleOrDefaultAsync();
string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
                + "FROM Person "
                + "WHERE Discriminator = 'Student' "
                + "GROUP BY EnrollmentDate";
IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);

ViewBag.RowsAffected = db.Database.ExecuteSqlCommand("UPDATE Course SET Credits = Credits * {0}", multiplier);


16.   Examining SQL sent to the database

IQueryable<Course> courses = db.Courses
              .Where(c => !SelectedDepartment.HasValue || c.DepartmentID == departmentID)
              .OrderBy(d => d.CourseID)
              .Include(d => d.Department);
var sql = courses.ToString();

17.   Fix error Newtonsoft.Json

Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)”

1.    Install newest newtonsoft.json

2.    Run command

uninstall-package newtonsoft.json -force
install-package newtonsoft.json

3.    Add below code to Web.config

<dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="8.0.0.0" />
</
dependentAssembly>

4.    Copy file from Referrence Propertices to bin folder

18.   Asynchronous - await Task.WhenAll
public async Task<ActionResult> PWGasync()
{
    ViewBag.SyncType = "Asynchronous";
    var widgetService = new WidgetService();
    var prodService = new ProductService();
    var gizmoService = new GizmoService();
 
    var widgetTask = widgetService.GetWidgetsAsync();
    var prodTask = prodService.GetProductsAsync();
    var gizmoTask = gizmoService.GetGizmosAsync();
 
    await Task.WhenAll(widgetTask, prodTask, gizmoTask);
 
    var pwgVM = new ProdGizWidgetVM(
       widgetTask.Result,
       prodTask.Result,
       gizmoTask.Result
       );
 
    return View("PWG", pwgVM);
}

19.   ?? Operator
// Set y to the value of x if x is NOT null; otherwise,
// if x = null, set y to -1.
int y = x ?? -1;
20.   Timestamp for handle conflict Concurrency
public class Department
{
    public int DepartmentID { get; set; }
 
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
 
    .......
 
    [Timestamp]
    public byte[] RowVersion { get; set; }
 
    .......
    public virtual ICollection<Course> Courses { get; set; }
}
The Timestamp attribute specifies that this column will be included in the Where clause of Update and Delete commands sent to the database

21.   [Authorize]
The Authorize filter checks to see if the user is authenticated. If the user is not authenticated, it returns HTTP status code 401 (Unauthorized) without invoking the action. You can apply the filter globally, at the controller level, or at the level of individual actions.

22.   the string that you want to display contains a backslash character (\) or double quotation marks ( " )
If the string that you want to display contains a backslash character (\) or double quotation marks ( " ), use a verbatim string literal that's prefixed with the @ operator. (In C#, the \ character has special meaning unless you use a verbatim string literal.)
@{ var myFilePath = @"C:\MyFolder\"; }
The path is: @myFilePath
To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
@myQuote
Here's the result of using both of these examples in a page:
Description: Razor-Img4


Không có nhận xét nào:

Đăng nhận xét