본문 바로가기
프로그래밍/ㄴ ASP

[웹사이트 제작] 2. 계정 생성 화면

by 뽀도 2020. 7. 11.

@View 화면

 

@컨트롤러 코드 

 

앞전에 만들었던 로그인 페이지에서 "CreateAccount" 버튼을 클릭하면 
LoginController의 httpGet CreateAccount() 함수를 호출 한다.

 

/// <summary>
/// 계정 생성 View 불러오는 함수 
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult CreateAccount()
{
	var model = new AccountModel();
	return View(model);
}

/// <summary>
/// 계정 생성 실행 함수 
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public ActionResult CreateAccount(AccountModel model)
{
	// View에서 보낸 Model 데이터의 유효성 체크 
	if (ModelState.IsValid)
	{
		try
		{
        	// 유효 하다면 DB를 오픈하여 account 테이블에 
            // 모델에서 넘어온 값을 입력 
			using(var db = new DBConnector())
			{

				var account = new Tbl_Account(model);
				Tbl_Account.InsertToDB(db.Connection, account);
			}

			// 성공시 계정 생성 성공을 alert창으로 알려주고
            // Login 화면으로 화면 이동
			return Content("<script language='javascript' type='text/javascript'>alert('계정 생성 성공, 로그인 하세요'); location.href='/Login/'</script>");
		}
		catch (Exception e)
		{
			var errorModel = new ErrorModel
			{
				ErrorStackTrace = e.StackTrace,
				ErrorMessage = e.Message,
			};
			// 에러가 나면 에러 내용을 Error 화면에 표시하기 위해
            // 다른 컨트롤러의 다른 액션으로 해당 데이터를 보낸다. 
			return RedirectToAction("Error", "Error", errorModel);
		}

	}
	else
	{
    	// 데이터가 유효하지 않다면 뷰에 받은 모델 그대로 리턴 
		return View(model);
	}
}

그리고 위의 함수와 같은 View를 찾아 웹 상에서 보여준다. 
그 화면이 위의 View 화면이다. 

 

@View 코드

@model GMS_FrameWork.Models.AccountModel

    @{
        ViewBag.Title = "Index";
    }

    <style>
        .validation-summary-errors {
            color: red;
        }

        .table td {
            text-align: center;
        }

        .table th {
            text-align: right;
        }
    </style>
    
    <div class="container">

        @using (Html.BeginForm("CreateAccount", "Login", FormMethod.Post))
        {
            <div class="card">

                <div class="card-header bg-primary text-white">Register</div>
                <div class="card-body">

                    <div class="d-flex justify-content-center">
                        @Html.ValidationSummary()
                    </div>

                    <div class="d-flex justify-content-center">
                        <table class="table table-borderless" style="width:500px;">
                            <tr>
                                <th>
                                    ID
                                </th>
                                <td>
                                    <input type="text" id="ID" class="form-control" name="ID">
                                </td>
                            </tr>

                            <tr>
                                <th>
                                    PW
                                </th>
                                <td>
                                    <input type="password" id="PW" class="form-control" name="PW">
                                </td>
                            </tr>

                            <tr>
                                <th>
                                    Name
                                </th>
                                <td>
                                    <input type="text" id="ID" class="form-control" name="Name">
                                </td>
                            </tr>

                            <tr>
                                <th>
                                    Team
                                </th>
                                <td>
                                    @Html.DropDownListFor(m => m.TeamType, Model.TeamTypes, "-- select --", new { @class = "form-control text-center ", @style = "text-align:center;", Name = "TeamType" })
                                </td>
                            </tr>

                            <tr>
                                <td colspan="2">
                                    <button type="submit" class="btn btn-outline-primary "> 계정 생성 </button>
                                </td>
                            </tr>

                        </table>
                    </div>

                </div>
            </div>

        }
    </div>

 

LoginController의 CreateAccount 함수로 데이터를 보내기 위해 

 

@using(Html.BeginForm("CreateAccount","Login", FormMethod.Post))

{

}

 

구문으로 필요 데이터를 감쌌다. 

 

그리고 혹시라도 필요한 데이터가 누락되는 것을 방지하기 위해 

 

@Html.ValidationSummary() 를 추가 하였다.
@Html.ValidationSummary()를 사용하면 모델에서 "Required"  Attribute로 지정한 부분이 누락되면 

View에서 에러 메시지를 띄워준다.

 

'계정 생성' 버튼을 누르면 LoginController의 HttpPost 전송으로 BeginForm안에 데이터를  CreateAccount 액션으로 보낸다. 

이때 주의할 점은 Name 설정이 Model의 변수이름과 같아야 우리가 원하는대로 동작 한다. 

 

@Model 부분

 public class AccountModel : IAccount
    {
        #region properties

        public int Idx { get; set; }

        [Required(ErrorMessage = "Please Enter your ID")]
        public string ID { get; set; }
        
        [Required(ErrorMessage = "Please Enter your Pw")]
        public string PW { get; set; }

        [Required(ErrorMessage = "Please choise your team")]
        public TeamType TeamType { get; set; }
        
        public IEnumerable<SelectListItem> TeamTypes { get; set; }

        [Required(ErrorMessage = "Please Enter your name")]
        public string Name { get; set; }

        public DateTime RegDate { get; set; }
        #endregion

        public AccountModel()
        {
            TeamTypes = GetTeamTypes();
        }

        IEnumerable<SelectListItem> GetTeamTypes(TeamType type = TeamType.Server)
        {
            var enumList = Util.ConvertEnumToList<TeamType>();

            bool selected = false;

            var selectList = new List<SelectListItem>();

            foreach (var team in enumList)
            {
                if (type == team)
                    selected = true;

                selectList.Add(new SelectListItem
                {
                    Value = ((int)team).ToString(),
                    Text = team.ToString(),
                    Selected = selected,
                });

                selected = false;
            }

            return selectList;
        }
    }

 

계정 정보 저장용 모델이다. IAccount 인터페이스를 상속받아 구현한다.

IAccount 인터페이스는 DB-Table용 클래스와 모델 클래스를 묶어주기 위해 정의 하여 사용하였다.

 

계정 생성에 필요한 정보를 변수로 정의하였다.

여기서 특이한 점은 View화면의 Team DropDownList를 사용하기 위해 GetTeamTypes()라는 함수를 정의한 부분이다.

 

잠시 View화면의 DropDownList를 구성해주는 코드를 보자. 


@Html.DropDownListFor(m => m.TeamType, Model.TeamTypes, "-- select --", new { @class = "form-control text-center ", @style = "text-align:center;", Name = "TeamType" })


@razor 코드를 사용하여 DropDownList를 구성하는데 
m->m.TeamType이 모델의 TeamType 변수이며,
Model.TeamTypes가 모델의 public IEnumerable<SelectListItem> TeamTypes { get; set; } 를 불러 오는 부분이다.

 

만약 Html 태그로 작성 했다면 아래의 방법으로 구현했을 텐데, html 태그보다 위의 코드가 편해서, 

@Html.DropDownListFor로 구현했다. 


<select name='fruits'>

  <option value='' selected>-- 선택 --</option>

  <option value='0'>Designer</option>

  <option value='1'>Client</option>

  <option value='2'>Server</option>

  <option value='3'>Art</option>

  <option value='4'>Manage</option>

</select>


그리고  TeamType 같은 경우 enum으로 다른 곳에 정의 하였다.

 

 public enum TeamType
    {
        [Display(Name = "기획")]
        Designer = 0,
        [Display(Name = "Client")]
        Client = 1,
        [Display(Name = "Server")]
        Server = 2,
        [Display(Name = "Art")]
        Art = 3,
        [Display(Name = "운영")]
        Manage = 4,
    }

 

그리고 GetTeamTypes() 함수 내부에 보면 

Util.ConvertEnumToList<TeamType>(); 라는 코드가 있는데 해당 코드는 

Enum을 IEnuIEnumerable<Enum>로 변환해주는 함수이다.

 public static IEnumerable<T> ConvertEnumToList<T>()
 {
 	var enumList = Enum.GetValues(typeof(T)).Cast<T>();
 	return enumList;
 }

코드 내에서 SelectList를 사용하는 경우가 많이 때문에 템플릿과 스태틱을 사용하여 정의 하여 사용하고 있다. 

 

 

Table 생성과 DB 연동 부분은 다음 포스트에 작성하겠다.

반응형

'프로그래밍 > ㄴ ASP' 카테고리의 다른 글

[C#][asp.net] file upload  (0) 2021.05.31
[웹사이트제작] 3. 페이징  (0) 2020.08.17
[ 웹사이트 제작] 1. Login 화면  (0) 2020.07.09
asp.net : 게시 설정 저장  (0) 2019.07.31
[asp] 프로젝트 생성하기  (0) 2017.01.10

댓글