Create ASP.NET MVC Project
On the Visual Studio, create new ASP.NET MVC Web Application project
Select Empty Template and Core Reference is MVC
Create Map Route
Open RouteConfig.cs file in App_Start folder, add new map route as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LearnASPNETMVCWithRealApps
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Demo", action = "Index", id = UrlParameter.Optional }
);
// New Map Route
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}/{id2}",
defaults: new { controller = "Demo", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional }
);
}
}
}
Create Controller
In Controllers folder, create new controller named DemoController.cs as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LearnASPNETMVCWithRealApps.Controllers
{
public class DemoController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Demo1(string id)
{
ViewBag.result = id;
return View("Result");
}
public ActionResult Demo2(int id, int id2)
{
ViewBag.result = id + id2;
return View("Result");
}
}
}
Create View
In Views/Demo folder, create new razor views as below:
Index View
Create new view named Index.cshtml as below:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>URL Parameters</h3>
<a href="@Url.Action("Demo1", "Demo", new { id = "p01" })">One Parameter</a>
<br />
<a href="@Url.Action("Demo2", "Demo", new { id = 4, id2 = 7 })">Multiple Parameters</a>
</body>
</html>
Result View
Create new view named Result.cshtml as below:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Result</title>
</head>
<body>
<h3>Result View</h3>
Id: @ViewBag.id
</body>
</html>
Structure of ASP.NET MVC Project
Run Application
Access Index action in Demo controller with following url: http://localhost:49328/Demo/Index
Output
Access Demo1 action in Demo controller with following url: http://localhost:49328/Demo/Demo1/p01
Output
Access Demo2 action in Demo controller with following url: http://localhost:49328/Demo/Demo2/4?id2=7
Output
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- ASP.NET MVC Framework Unleashed
- Programming Microsoft ASP.NET MVC (3rd Edition) (Developer Reference)
- Pro ASP.NET MVC 5 Platform
- Pro ASP.NET MVC Framework
- Professional ASP.NET MVC 5