본문 바로가기

대돌이의 하루/ASP

asp .net 모델바인딩 하기

뷰에서 작성한 데이터를 
컨트롤러로 보낼때 
모델 바인딩을 통해서 처리할 수 있다

 

http post 요청에서
input 이나

 

-

바인딩을 통하여, 받고싶지 않은 데이터들을 null값으로 받을 수 있다.

 

-

확인방법 : 

 

해당 컨트롤러 파일을 디버깅을 통하여 확인 할 수 있음

 

첫번째방법. 

Contreoller, 해당 cs에서 바인딩하기

namespace WebApplication3.Controllers 
{ 
    public class HomeController : Controller 
    { 
        //레이저 파일을 보여주는 역할 
        public IActionResult student() 
        { 
            return View(); 
        } 

        //포스트특성이 있는 액션함수를 만든다 (html view 넘어온 값들을 받는 역할을 한다) 
        [HttpPost] 
       
        //바인딩을 통해 받고싶은 데이터만 가려 낼 수 있다 
        public IActionResult Student([Bind("Name,Age")] Student model) 
        { 
            return View(); 
        }
    } 
}

 

2번째방법. 

Model에서 직접 바인딩하기

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication3.Models
{

    //input 필드에 내용들과 매칭들을 속성들을 넣어준다
    public class Student
    {
        [BindNever]
        public string Name { get; set; }
        public int Age { get; set; }
        public string Country { get; set; }
    }
}