제 의견으로는 MVC 프로젝트에있는 ViewModel과 뷰에 렌더링되는 두 개의 "모델"로 작업해야합니다. 그리고 비즈니스 로직 계층의 두 번째 EntityModel. 이것은 표준 "엔터프라이즈"프로그래밍 설계입니다. 그것은 당신에게 당신의 데이터에 대한 더 많은 통제를 제공합니다. 아이디어는 이것입니다.
UI 조립 (MVC 프로젝트)
뷰 모델 정의
public class MyModel {
public int ID { get; set; }
.... // bunch of other properties
}
컨트롤러
public class InterestingController : Controller {
public ActionResult CreateNewWidget() {
var model = new MyModel();
return View(model);
}
[HttpPost]
public ActionResult CreateNewWidget(MyModel model) {
if(ModelState.IsValid) {
// your ctor can define the order of your properties being sent in and you can set the entity values in the ctor body however you choose to. Note never SET an ID/Primary key on a Create, let the DB handle that. If you need to return the new Key value, get it from the insert proc method in your DAL and return it up the stack
var entityModel = new EntityFromBLL(model.Name, model.OtherProperty, ... etc);
entityModel.Save(User.Identity.Name); // your save method should always capture WHO is doing the action
}
return View(model);
}
public ActionResult UpdateExistingWidget(int id) {
var entityModel = new EntityFromBLL(id); // get the existing entity from the DB
var model = new MyModel(entityModel.ID, entityModel.Name, ... etc); // populate your ViewModel with your EntityModel data in the ViewModel ctor - note remember to also create a parameterless default ctor in your ViewModel as well anytime you create a ctor in a ViewModel that accepts parameters
return View(model);
}
[HttpPost]
public ActionResult UpdateExistingWidget(MyModel model) {
if(ModelState.IsValid) {
var entityModel = new EntityFromBLL(model.ID); // always pull back your original data from the DB, in case you deal with concurrency issues
// now go thru and update the EntityModel with your new ViewModel data
entityModel.Name = model.Name;
//... etc set all the rest of the properties
// then call the save
entityModel.Save(User.Identity.Name);
}
return View(model)
}
}
귀하의 엔티티 모델은 민간 분야, 공용 속성, 모든 소요 ctor에 정의되어야한다
삽입 (기본 키 빼기)을위한 필수 필드, 기본 키를 가져 와서 내부로드 메소드를 정적으로 호출하여 채워진 객체를 반환 할 수있는 ctor 목적. 비즈니스 규칙 및 속성 유효성 검사 및 단일 Save 메서드 Save 메서드는 모든 속성을 설정 한 후 IsDirty 비트를 확인하고 해당 Insert 또는 Update 메서드를 호출해야합니다. 그러면 DTO를 전달하는 DAL을 차례로 호출해야합니다.
사용자 지정 ModelBinder를 만들어야 할 수도 있습니다 필요합니다. –
이 양식은 많은 양의 데이터를 게시합니다. 어쨌든 모든 속성을 설정하지 않고도 사용자 정의 모델 바인더를 수행 할 수 있습니까? I.E. 내가 설정할 수있는 속성을 설정하고 나머지는 기본 처리하도록 하시겠습니까? – PlTaylor
기본 공급자를 상속하면 대부분 그렇습니다. 이 스레드를 확인하십시오 : http://stackoverflow.com/questions/3636747/asp-net-mvc-custom-model-binder-for-id-fields 목표는 기본 모델 바인더에서 상속하고 ID 필드를 채 웁니다. 먼저, base.BindModel (controllerContext, bindingContext)을 사용하십시오. –