2013-03-01 4 views
1

MVC 아키텍처와 Entity Framework (데이터베이스 우선)를 사용하여 인트라넷 ASP 웹 응용 프로그램을 개발하고 있습니다. 내 문제는 다음과 같습니다.부분보기에서 모델 데이터 가져 오기

"Person"과 "Person"(즉, Id_Person)의 기본 키를 외래 키로 포함하는 "PhoneCard"엔티티가 있습니다. Entity Framework를 사용하여 CRUD 컨트롤러 "PersonController"를 만들었고 Visual Studio에서 자동으로 해당보기 (색인, 세부 정보, 작성, 편집 및 삭제)를 생성했습니다. 그런 다음, "PhoneCardController"라는 다른 CRUD 컨트롤러 (항상 EF 사용)를 만들었습니다.

function addPhoneCardCreateView() { 

    $('#divCreatePhoneCard').load("@Url.Action("Create","PhoneCard")"); 

} 

그리고 다음과 같이 호출 :이, 나는 내가 할 수있는 나의 부분 뷰를 호출함으로써

<a href = "javascript:addPhoneCardCreateView()">Add a Phone card</a> 
    <div id = "divCreatePhoneCard"></div> 

을 내 만들기 사람이보기에, 나는이 AJAX 기능에 전화 카드보기 감사를 만들기 포함 내가 사람을 추가하는 동안 전화 카드를 추가하십시오. 불행히도 Create 버튼을 클릭하면 새로운 사람 만 데이터베이스에 추가됩니다. 여기 내 PersonController에서 작성 작업은 다음과 같습니다

 public ActionResult Create() 
    { 
     ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name"); 
     return View(); 
    } 

    // 
    // POST: /Person/Create 

    [HttpPost] 
    public ActionResult Create(Person person) 
    { 
     if (ModelState.IsValid) 
     { 

      db.Persons.AddObject(person); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory); 
     return View(person); 
    } 

내 부분보기 :

@model BuSIMaterial.Models.PhoneCard 

@{ 
    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Create</title> 
</head> 
<body> 
    <script src="~/Scripts/jquery-1.7.1.min.js"></script> 
    <script src="~/Scripts/jquery.validate.min.js"></script> 
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

    @using (Html.BeginForm()) { 
     @Html.ValidationSummary(true) 

     <fieldset> 
      <legend>PhoneCard</legend> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.PhoneNumber) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.PhoneNumber) 
       @Html.ValidationMessageFor(model => model.PhoneNumber) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.SimNumber) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.SimNumber) 
       @Html.ValidationMessageFor(model => model.SimNumber) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.PIN) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.PIN) 
       @Html.ValidationMessageFor(model => model.PIN) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.PIN2) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.PIN2) 
       @Html.ValidationMessageFor(model => model.PIN2) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.PUK) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.PUK) 
       @Html.ValidationMessageFor(model => model.PUK) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.PUK2) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.PUK2) 
       @Html.ValidationMessageFor(model => model.PUK2) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.Id_Person, "Person") 
      </div> 
      <div class="editor-field"> 
       @Html.DropDownList("Id_Person", String.Empty) 
       @Html.ValidationMessageFor(model => model.Id_Person) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.Id_PhoneSubscription, "PhoneSubscription") 
      </div> 
      <div class="editor-field"> 
       @Html.DropDownList("Id_PhoneSubscription", String.Empty) 
       @Html.ValidationMessageFor(model => model.Id_PhoneSubscription) 
      </div> 
     </fieldset> 
    } 

</body> 
</html> 

사람 모델 :

[EdmEntityTypeAttribute(NamespaceName="BuSIMaterialModel", Name="Person")] 
[Serializable()] 
[DataContractAttribute(IsReference=true)] 
public partial class Person : EntityObject 
{ 
    #region Factory Method 

    /// <summary> 
    /// Create a new Person object. 
    /// </summary> 
    /// <param name="id_Person">Initial value of the Id_Person property.</param> 
    /// <param name="firstName">Initial value of the FirstName property.</param> 
    /// <param name="lastName">Initial value of the LastName property.</param> 
    /// <param name="numNat">Initial value of the NumNat property.</param> 
    /// <param name="startDate">Initial value of the StartDate property.</param> 
    /// <param name="upgrade">Initial value of the Upgrade property.</param> 
    /// <param name="id_ProductPackageCategory">Initial value of the Id_ProductPackageCategory property.</param> 
    /// <param name="houseToWorkKilometers">Initial value of the HouseToWorkKilometers property.</param> 
    public static Person CreatePerson(global::System.Int64 id_Person, global::System.String firstName, global::System.String lastName, global::System.String numNat, global::System.DateTime startDate, global::System.Boolean upgrade, global::System.Int64 id_ProductPackageCategory, global::System.Decimal houseToWorkKilometers) 
    { 
     Person person = new Person(); 
     person.Id_Person = id_Person; 
     person.FirstName = firstName; 
     person.LastName = lastName; 
     person.NumNat = numNat; 
     person.StartDate = startDate; 
     person.Upgrade = upgrade; 
     person.Id_ProductPackageCategory = id_ProductPackageCategory; 
     person.HouseToWorkKilometers = houseToWorkKilometers; 
     return person; 
    } 

    #endregion 
    #region Primitive Properties 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] 
    [DataMemberAttribute()] 
    public global::System.Int64 Id_Person 
    { 
     get 
     { 
      return _Id_Person; 
     } 
     set 
     { 
      if (_Id_Person != value) 
      { 
       OnId_PersonChanging(value); 
       ReportPropertyChanging("Id_Person"); 
       _Id_Person = StructuralObject.SetValidValue(value); 
       ReportPropertyChanged("Id_Person"); 
       OnId_PersonChanged(); 
      } 
     } 
    } 
    private global::System.Int64 _Id_Person; 
    partial void OnId_PersonChanging(global::System.Int64 value); 
    partial void OnId_PersonChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    [Required] 
    public global::System.String FirstName 
    { 
     get 
     { 
      return _FirstName; 
     } 
     set 
     { 
      OnFirstNameChanging(value); 
      ReportPropertyChanging("FirstName"); 
      _FirstName = StructuralObject.SetValidValue(value, false); 
      ReportPropertyChanged("FirstName"); 
      OnFirstNameChanged(); 
     } 
    } 
    private global::System.String _FirstName; 
    partial void OnFirstNameChanging(global::System.String value); 
    partial void OnFirstNameChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    [Required] 
    public global::System.String LastName 
    { 
     get 
     { 
      return _LastName; 
     } 
     set 
     { 
      OnLastNameChanging(value); 
      ReportPropertyChanging("LastName"); 
      _LastName = StructuralObject.SetValidValue(value, false); 
      ReportPropertyChanged("LastName"); 
      OnLastNameChanged(); 
     } 
    } 
    private global::System.String _LastName; 
    partial void OnLastNameChanging(global::System.String value); 
    partial void OnLastNameChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    [Required] 
    public global::System.String NumNat 
    { 
     get 
     { 
      return _NumNat; 
     } 
     set 
     { 
      OnNumNatChanging(value); 
      ReportPropertyChanging("NumNat"); 
      _NumNat = StructuralObject.SetValidValue(value, false); 
      ReportPropertyChanged("NumNat"); 
      OnNumNatChanged(); 
     } 
    } 
    private global::System.String _NumNat; 
    partial void OnNumNatChanging(global::System.String value); 
    partial void OnNumNatChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    public global::System.DateTime StartDate 
    { 
     get 
     { 
      return _StartDate; 
     } 
     set 
     { 
      OnStartDateChanging(value); 
      ReportPropertyChanging("StartDate"); 
      _StartDate = StructuralObject.SetValidValue(value); 
      ReportPropertyChanged("StartDate"); 
      OnStartDateChanged(); 
     } 
    } 
    private global::System.DateTime _StartDate; 
    partial void OnStartDateChanging(global::System.DateTime value); 
    partial void OnStartDateChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] 
    [DataMemberAttribute()] 
    public Nullable<global::System.DateTime> EndDate 
    { 
     get 
     { 
      return _EndDate; 
     } 
     set 
     { 
      OnEndDateChanging(value); 
      ReportPropertyChanging("EndDate"); 
      _EndDate = StructuralObject.SetValidValue(value); 
      ReportPropertyChanged("EndDate"); 
      OnEndDateChanged(); 
     } 
    } 
    private Nullable<global::System.DateTime> _EndDate; 
    partial void OnEndDateChanging(Nullable<global::System.DateTime> value); 
    partial void OnEndDateChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    public global::System.Boolean Upgrade 
    { 
     get 
     { 
      return _Upgrade; 
     } 
     set 
     { 
      OnUpgradeChanging(value); 
      ReportPropertyChanging("Upgrade"); 
      _Upgrade = StructuralObject.SetValidValue(value); 
      ReportPropertyChanged("Upgrade"); 
      OnUpgradeChanged(); 
     } 
    } 
    private global::System.Boolean _Upgrade; 
    partial void OnUpgradeChanging(global::System.Boolean value); 
    partial void OnUpgradeChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    [Required] 
    public global::System.Int64 Id_ProductPackageCategory 
    { 
     get 
     { 
      return _Id_ProductPackageCategory; 
     } 
     set 
     { 
      OnId_ProductPackageCategoryChanging(value); 
      ReportPropertyChanging("Id_ProductPackageCategory"); 
      _Id_ProductPackageCategory = StructuralObject.SetValidValue(value); 
      ReportPropertyChanged("Id_ProductPackageCategory"); 
      OnId_ProductPackageCategoryChanged(); 
     } 
    } 
    private global::System.Int64 _Id_ProductPackageCategory; 
    partial void OnId_ProductPackageCategoryChanging(global::System.Int64 value); 
    partial void OnId_ProductPackageCategoryChanged(); 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] 
    [DataMemberAttribute()] 
    public global::System.Decimal HouseToWorkKilometers 
    { 
     get 
     { 
      return _HouseToWorkKilometers; 
     } 
     set 
     { 
      OnHouseToWorkKilometersChanging(value); 
      ReportPropertyChanging("HouseToWorkKilometers"); 
      _HouseToWorkKilometers = StructuralObject.SetValidValue(value); 
      ReportPropertyChanged("HouseToWorkKilometers"); 
      OnHouseToWorkKilometersChanged(); 
     } 
    } 
    private global::System.Decimal _HouseToWorkKilometers; 
    partial void OnHouseToWorkKilometersChanging(global::System.Decimal value); 
    partial void OnHouseToWorkKilometersChanged(); 

    #endregion 

    #region Navigation Properties 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [XmlIgnoreAttribute()] 
    [SoapIgnoreAttribute()] 
    [DataMemberAttribute()] 
    [EdmRelationshipNavigationPropertyAttribute("BuSIMaterialModel", "FK_bm_Persons_bm_ProductPackageCategories", "bm_ProductPackageCategories")] 
    public ProductPackageCategory ProductPackageCategory 
    { 
     get 
     { 
      return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<ProductPackageCategory>("BuSIMaterialModel.FK_bm_Persons_bm_ProductPackageCategories", "bm_ProductPackageCategories").Value; 
     } 
     set 
     { 
      ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<ProductPackageCategory>("BuSIMaterialModel.FK_bm_Persons_bm_ProductPackageCategories", "bm_ProductPackageCategories").Value = value; 
     } 
    } 
    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [BrowsableAttribute(false)] 
    [DataMemberAttribute()] 
    public EntityReference<ProductPackageCategory> ProductPackageCategoryReference 
    { 
     get 
     { 
      return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<ProductPackageCategory>("BuSIMaterialModel.FK_bm_Persons_bm_ProductPackageCategories", "bm_ProductPackageCategories"); 
     } 
     set 
     { 
      if ((value != null)) 
      { 
       ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<ProductPackageCategory>("BuSIMaterialModel.FK_bm_Persons_bm_ProductPackageCategories", "bm_ProductPackageCategories", value); 
      } 
     } 
    } 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [XmlIgnoreAttribute()] 
    [SoapIgnoreAttribute()] 
    [DataMemberAttribute()] 
    [EdmRelationshipNavigationPropertyAttribute("BuSIMaterialModel", "FK_bm_PhoneCards_bm_Persons", "bm_PhoneCards")] 
    public EntityCollection<PhoneCard> PhoneCards 
    { 
     get 
     { 
      return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<PhoneCard>("BuSIMaterialModel.FK_bm_PhoneCards_bm_Persons", "bm_PhoneCards"); 
     } 
     set 
     { 
      if ((value != null)) 
      { 
       ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<PhoneCard>("BuSIMaterialModel.FK_bm_PhoneCards_bm_Persons", "bm_PhoneCards", value); 
      } 
     } 
    } 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [XmlIgnoreAttribute()] 
    [SoapIgnoreAttribute()] 
    [DataMemberAttribute()] 
    [EdmRelationshipNavigationPropertyAttribute("BuSIMaterialModel", "FK_bm_ProductAllocations_bm_Persons", "bm_ProductAllocations")] 
    public EntityCollection<ProductAllocation> ProductAllocations 
    { 
     get 
     { 
      return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ProductAllocation>("BuSIMaterialModel.FK_bm_ProductAllocations_bm_Persons", "bm_ProductAllocations"); 
     } 
     set 
     { 
      if ((value != null)) 
      { 
       ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ProductAllocation>("BuSIMaterialModel.FK_bm_ProductAllocations_bm_Persons", "bm_ProductAllocations", value); 
      } 
     } 
    } 

    /// <summary> 
    /// No Metadata Documentation available. 
    /// </summary> 
    [XmlIgnoreAttribute()] 
    [SoapIgnoreAttribute()] 
    [DataMemberAttribute()] 
    [EdmRelationshipNavigationPropertyAttribute("BuSIMaterialModel", "FK_bm_VehicleFuelCards_bm_Persons", "bm_VehicleFuelCards")] 
    public EntityCollection<VehicleFuelCard> VehicleFuelCards 
    { 
     get 
     { 
      return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<VehicleFuelCard>("BuSIMaterialModel.FK_bm_VehicleFuelCards_bm_Persons", "bm_VehicleFuelCards"); 
     } 
     set 
     { 
      if ((value != null)) 
      { 
       ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<VehicleFuelCard>("BuSIMaterialModel.FK_bm_VehicleFuelCards_bm_Persons", "bm_VehicleFuelCards", value); 
      } 
     } 
    } 

    #endregion 
} 
+0

PhoneCard 부분보기는 어떻게 보이나요? –

+0

방금 ​​게시 한 부분보기 =) – Traffy

+0

'Person'과'PhoneCard' 모델을 보여줄 수 있습니까? –

답변

2

귀하의 Person 모델은 항상 널 (null) 인 컬렉션 속성 PhoneCards있다 naming convention for binding to a list을 존중하지 않았기 때문에 게시 작업. 또한 PhoneCard.cshtml은 부분보기는 아니지만 전면보기 (<html><body> 태그가 잘못됨)입니다.

스티브 샌더슨이이를 달성하는 방법을 자세히 설명하는 following article을 정말로 권합니다. 동적으로 추가 및 제거 할 수 있도록 입력 필드의 이름에 비 순차 색인을 생성하기 위해 사용자 정의 Html.BeginCollectionItem 도우미를 사용합니다.

+0

튜토리얼을 보내 주셔서 감사합니다. 그러나 여전히 질문이 있습니다. "목록에 바인딩하기위한 명명 규칙을 존중하지 않았습니다"라는 것이 무슨 뜻입니까? 이 코드는 모두 VS에 의해 자동으로 생성 되었기 때문입니다. – Traffy

+0

다음 기사를 살펴보십시오. http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx ASP.NET MVC는 모델 바인더를 사용하여 작업 매개 변수를 바인딩합니다 요청에서. 즉, 양식 내부에있는 입력 필드는이 규칙을 준수해야합니다. 코드가 자동으로 생성되었다고해서 그것이 작동해야한다는 것을 의미하지는 않습니다. –