Razor Frontend model binding

FGPRJS·2022년 6월 8일
0

Razor를 사용한 Frontend의 model binding에 관한 건


1. MVC5+에서 제공하는 모델 사용법

다음 링크를 참고하여 razor frontend와 model을 바인딩 하는 방식에 대해 참조한다.


다음 cshtml파일을 참고한다.

@page 
@model ModelBindingModel
@{
}
<h3>@ViewData["confirmation"]</h3>
<form class="form-horizontal" method="post">
    <div class="form-group">
        <label for="Name" class="col-sm-2 control-label">Name</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="Name">
        </div>
    </div>
    <div class="form-group">
        <label for="Email" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="Email">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default">Register</button>
        </div>
    </div>
</form>

위 cshtml에서의 데이터 정보의 예시는 다음과 같다.

Name이라는 name을 갖는 text타입의 input의 Value는 Mike이다.

Email이라는 name을 갖는 text 타입의 input의 Value는 info@leanrazorpages.com이다.

이제, 이런 cshtml을 갖는 페이지의 입력을 클래스로 받을 수 있는 모델을 만들어본다.

public class ModelBindingModel : PageModel
{
    [BindProperty]
    public string Name { get; set; }
    [BindProperty]
    public string Email { get; set; }
    public void OnGet()
    {
    }
    public void OnPost()
    {
        ViewData["confirmation"] = $"{Name}, information will be sent to {Email}";
    }
}

2. MVC3+에서 제공하는 Model 사용법

MVC3+에서 제공하는 Model 폴더에 대한 Model에 대한 정보는 다음 링크를 참조한다.


using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }

        [Required(ErrorMessage = "Title is required")]
        public string Title { get; set; }

        public DateTime ReleaseDate { get; set; }

        [Required(ErrorMessage = "Genre must be specified")]
        public string Genre { get; set; }

        [Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
        public decimal Price { get; set; }

        [StringLength(5)]
        public string Rating { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}
profile
FGPRJS

0개의 댓글