ASP.NET/MVC 5

ASP.NET MVC 5 기본

littlemk 2018. 7. 20. 10:54

  1. 프로젝트 생성





  1. Controller 추가하기







! 컨트롤러 생성 시, 자동으로 스캐폴딩(CRUD 자동생성) 해줌



  1. 방금 생성한 HelloWorldController 소스 변경

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcMovie.Controllers
{
    public class HelloWorldController : Controller
    {
        // GET: HelloWorld
        public string Index()
        {
                     return "This is my <b>default</b> action..";
        }
              //
              // GET : /HelloWorld/Welcome/
              public string Welcome()
              {
                     return "This is the Welcome action method..";
              }
    }
}

 
[localhost:xxxx/HelloWorld]                        [localhost:xxxx/HelloWorld/Welcome]
 





# ASP.NET MVC 기본 URL 라우팅 로직

:: /[Controller]/[ActionName]/[Parameters]


[App_Start/RouteConfig.cs 기본파일]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcMovie
{
       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 = "Home", action = "Index", id = UrlParameter.Optional }
                     );
              }
       }
}

/*
    기본 default 컨트롤러는 Home으로 되어있다. 
*/


  1. /[Controller]/[ActionName]/[Parameters] 사용해보기


현재 URL localhost:xxxx/HelloWorld/Welcome/은 Controller와 Action 매서드를 사용중이지만, Parameters는 사용하고 있지 않고 있다.

때문에 다음 예제에서 parameters를 사용해보도록 하자.



  1. (localhost:xxxx/HelloWorld/Welcome?name=Scott&NumTimes=3) 라는 다음 코드처럼, 두 개의 매개변수를 전달받도록 HelloWorld 컨트롤러의 Welcome 액션 메서드를 수정해보자.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcMovie.Controllers
{
    public class HelloWorldController : Controller
    {
        // GET: HelloWorld
        public string Index()
        {
                     return "This is my <b>default</b> action..";
        }
              //
              // GET : /HelloWorld/Welcome/
              public string Welcome(string name, int numTimes = 1)
              {
                     return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
              }
    }
}
/*
    악의적인 사용자의 입력으로부터 응용프로그램을 보호하기위해 HttpServerUtility.HtmlEncode 메서드를 사용함.
*/




  1. url에서 localhost:xxxx/HelloWorld/Welcome?name=Scott&NumTimes=3 을 입력



-> 위의 예제는 매개변수 값을 전달하기 위해서 URL 세그먼트를 이용하는 대신,
쿼리 문자열로 name 매개변수와 numTimes 매개변수를 전달하고 있다.

위의 URL 주소에서 물음표(?)는 구분자 역할을 하며, 물음표 뒤에 나타는 문자열들이 쿼리 문자열이다.

앰퍼샌드(&) 문자는 각각의 쿼리 문자열을 서로 구분해주는 역할을 한다.



  1. Welcome 액션 메서드 소스 수정

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcMovie.Controllers
{
    public class HelloWorldController : Controller
    {
        // GET: HelloWorld
        public string Index()
        {
                     return "This is my <b>default</b> action..";
        }
              //
              // GET : /HelloWorld/Welcome/
              public string Welcome(string name, int id = 1)
              {
                     return HttpUtility.HtmlEncode("Hello " + name + ", id is: " + id);
              }
    }
}


  1. localhost:xxxx/HelloWorld/3?name=Rick 입력




=> 보통 쿼리 문자열을 통해 매개변수를 전달하는 방식보다는 라우트 데이터의 형태로 매개변수를 전달하는 것이 일반적이다.




  1. RouteConfig.cs 소스 수정
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcMovie
{
       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 = "Home", action = "Index", id = UrlParameter.Optional }
                     );
                     routes.MapRoute(
                           name: "Hello",
                           url: "{controller}/{action}/{name}/{id}"
                     );
              }
       }
}



일반적인 경우 컨트롤러에서 HTML을 직접 반환하진 않는다. 
직접 반환하지 않을 시 코드가 매우 길고 복잡해지기 때문이다. 

HTML 응답을 생성하기 위해 별도의 뷰 템플릿을 사용하는 것이 보다 일반적인 방법이다. 


참고 사이트 :: http://www.egocube.pe.kr/translation/content/asp-net-mvc-5-tutorial-1/201504200001