Custom route in ASP.NET MVC

Đoạn code dưới đây hướng dẫn cách định nghĩa Custom Route trong ASP.NET MVC

Để định nghĩa route mới, vào file ~/App_Start/RouteConfig.cs và định nghĩa route mới ngay sau dòng lệnh routes.IgnoreRoute

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Admin",
                url: "Admin/{action}/{id}",
                defaults: new { controller = "Admin", action = "Create", id
= UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
            );
        }
    }

Lưu ý: là Route mặc định luôn để cuối cùng sau tất cả các route khác, nếu để route mặc định lên đầu tiên thì các route định nghĩa sau route default sẽ không được thực hiện.

ASP.NET MVC Upload file

ASP.NET MVC Upload file – Đoạn mã dưới đây hướng dẫn cách upload file trong ASP.NET MVC

Entity class

public class FileInformation
{
public string FileName { get; set; }
public string CreatedDate { get; set; }
}

Controller

public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload([Bind(Include =”FileName,CreatedDate”)] FileInformation file,
HttpPostedFileBase File1)
{
string path = Server.MapPath(“~/Uploads/”);

//Lấy phần mở rộng của file
string extensionName = System.IO.Path.GetExtension(File1.FileName);
// Tạo tên file ngẫu nhiên
string finalFileName = DateTime.Now.Ticks.ToString() + extensionName;
// Upload file lên server
File1.SaveAs(path + finalFileName);

//Làm gì đó với thông tin của file – lưu đường dẫn vào csdl chẳng hạn
file.FileName = finalFileName;
file.CreatedDate = DateTime.Today.ToShortDateString();
ViewBag.FileInfor = file;
return View(“Uploaded”);
}

Hiển thị thông tin file sau upload

@{
ViewBag.Title = “Uploaded”;
}
@{
var fi = (RoleBasedSecurityMVC5.Models.FileInformation)ViewBag.FileInfor;
}

<h2>Uploaded – File Information</h2>
<hr/>
<h3>File name: @fi.FileName</h3>
<h3>Created Date: @fi.CreatedDate</h3>

ASP.NET MVC Get submit data

Đoạn mã dưới đây dùng FormCollection để đọc dữ liệu submit từ form lên server (ASP.NET MVC)

View:

@{
var list =new[] { “New York”, “Philadelphia”, “California” };
}

@*@using (Html.BeginForm(“Register”,”Home”,FormMethod.Post))*@
@using (Html.BeginForm())
{

@Html.Label(“User Name:”)<br/>
@Html.TextBox(“UserName”)<br/><br/>
@Html.Label(“Address:”)<br/> @Html.TextArea(“Address”)<br/><br/>
@Html.Label(“Password:”)<br/>@Html.Password(“Password”)<br/><br/>
@Html.Label(“I need updates on my mail:”)
@Html.CheckBox(“ChkEmail”)<br/> <br/>
@Html.Label(“Select your city:”)
@Html.DropDownList(“City”, new SelectList(list), “Choose”) <br/>
@Html.Label(“Male:”)@Html.RadioButton(“Gender”, “Male”, true) <br/>
@Html.Label(“Female:”)@Html.RadioButton(“Gender”, “Female”) <br/> <br/>
<br/><br/>
<input type=”submit” value=”Submit”>
}

Controller:

public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(FormCollection fields)
{
string username = fields[“UserName”];
string address = fields[“Address”];
string password = fields[“Password”];
//string email = fields[“ChkEmail”];
bool email = fields[“ChkEmail”] == “false” ? false : true;
//Get value of checkbox

string city = fields[“City”];
string gender = fields[“Gender”];
ViewBag.UserName = username;
ViewBag.Address = address;
ViewBag.Password = password;
ViewBag.Email = email;
ViewBag.City = city;
ViewBag.Gender = gender;
return View(“RegistrationInfo”);
}

Set SelectedIndex for DataGridViewComboBoxCell

Đoạn code sau hướng dẫn cách thiết lập DataGridViewComboBox Column trong windows Forms

DataTable dt = null;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add(“Category”);
DataRow dr = dt.NewRow();
dr[“Category”] = “Select All”;
dt.Rows.Add(dr);
DataRow row = dt.NewRow();
row[0] = “Cat 1”;
dt.Rows.Add(row);
DataRow row2 = dt.NewRow();
row2[0] = “Cat 2”;
dt.Rows.Add(row2);
DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn();
newColumn.Name = “Category”;
newColumn.DataSource = dt;
newColumn.DisplayMember = “Category”;
newColumn.ValueMember = “Category”;
dataGridView1.Columns.Add(newColumn);
}

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = dt.Rows[0][0].ToString();
}

Script check database and table was existed

Script check database and table was existed

DECLARE @dbname nvarchar(128)
SET @dbname = N’dbTest5′

IF (EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE (‘[‘ + name + ‘]’ = @dbname OR name = @dbname)))
begin
use master
drop database dbtest5
end
go
create database dbtest5
go

use dbtest5
go

— Run this script at any time, either to:
— (a) Create the demo tables in a different database (see note in previous example)
— (b) Restore the demo tables to their original state

if exists (select * from sysobjects where name = ‘PurchaseItem’) drop table PurchaseItem
if exists (select * from sysobjects where name = ‘Purchase’) drop table Purchase
if exists (select * from sysobjects where name = ‘Customer’) drop table Customer
if exists (select * from sysobjects where name = ‘MedicalArticles’) drop table MedicalArticles
if exists (select * from sysobjects where name = ‘Product’) drop table Product
go

create table Customer
(
ID int not null primary key,
Name nvarchar(30) not null
)

create table Purchase
(
ID int not null primary key,
CustomerID int null references Customer (ID),
Date datetime not null,
Description varchar(30) not null,
Price decimal not null
)

create table PurchaseItem
(
ID int not null primary key,
PurchaseID int not null references Purchase (ID),
Detail varchar(30) not null,
Price decimal not null
)

create table MedicalArticles
(
ID int not null primary key,
Topic varchar (20),
Abstract nvarchar (2000)
)

create table Product
(
ID int not null primary key,
Description varchar(30) not null,
Discontinued bit not null,
LastSale datetime not null
)

Table per hierarchy – type 1

public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
}
public class OnlineCourse : Course
{
public string URL { get; set; }
}
public class OfflineCourse : Course
{
public string Address { get; set; }
}

public class TPHContext:DbContext
{
public DbSet<Course> Courses { get; set; }
public TPHContext() : base(“TPH”)
{
Database.SetInitializer<TPHContext>(new DropCreateDatabaseIfModelChanges<TPHContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>()
.Map<OnlineCourse>(m => m.Requires(“Type”).HasValue(“OnlineCourse”))
.Map<OfflineCourse>(m => m.Requires(“Type”).HasValue(“OfflineCourse”));
}
}