2013-07-17 2 views
0

얘들 아 하나 이상의 모델을 단일보기로 사용하려고했습니다.하나 이상의 모델을 단일보기로 바인딩하는 방법은 무엇입니까?

하지만 구현 방법을 찾을 수 없습니다.

나는이 하나 개의보기

@Html.Partial("Sidebar") 

이있다

나는 다음과 같은 코드를 사용했다

단일 과거와 다른 부분에서 다른에 하나의 데이터보기를 ... ... 사용하려면 다른보기입니다

<!-- start content --> 
    <div id="content"> 
     <div class="post"> 
      <h1 class="title"> 
       Add New Post 
      </h1> 

<p></p> 
      <div class="entry"> 
       @using (Html.BeginForm()) 
       { 
        <div> 
         <div style="display:inline;"> 
          <div style="display: inline; float: left;"> 
           @Html.Label("lblcategory", "Category", new { style = "Width:100px; float: left;" }) 
           <div style="width: 150px; height: 60px; overflow-y: scroll; display: inline; float: left;"> 
            @for (int i = 0; i < (int)TempData["Rows"]; i++) 
            { 
             for (int j = 0; j < (int)TempData["Cols"]; j++) 
             { 
              <input id="Checkbox + @i" name = "Category" type="checkbox" style="width:50px;" value="@TempData["[" + i.ToString() + "][" + j.ToString() + "]"]"/> 
              @TempData["[" + i.ToString() + "][" + j.ToString() + "]"] 
             } 
            }         
            @*@Html.LabelFor(model => model.CategoryName)*@ 
           </div> 
           <div style="float:right;"> 
            <label id="lblcategoryrequired" style="color:Red">@Html.ValidationMessageFor(model => model.CategoryName)</label> 
           </div> 
          </div> 
         </div> 
         <div> 
          <p style="display: inline; float: left;"> 
           @Html.Label("lblsubjet", "Subject", new { style = "Width:100px; float: left;" }) 
           @*@Html.TextBox("txtsubject", "", new { style = "Width:700px;" })*@ 
           @Html.TextBoxFor(model => model.PostSubject, new { style = "Width:400px; maxlength=400;" }) 
           <label id="lblsubjectrequired" style="color:Red">@Html.ValidationMessageFor(model => model.PostSubject)</label> 
          </p> 
         </div> 
         <div> 
          <p style="display: inline; float: left;"> 
           @Html.Label("lblcontent", "Content", new { style = "Width:100px; float: left; Vertical-align:top;" }) 
           @*@Html.TextArea("txtcontent","", new { style = "Width:700px; height:200px; maxlength=700;" })*@ 
           @Html.TextAreaFor(model => model.PostContent, new { style = "Width:400px; height:200px; maxlength=400;" }) 
          </p> 
         </div> 
         <div> 
          <p style="display: inline; float: left;"> 
           @Html.Label("lblblank", "a", new { style = "Width:100px; float: left; Color:#372412" }) 
           <input type="submit" value="Add" id="btnadd" style="width: 100px;" class="button" /> 
           &nbsp&nbsp&nbsp&nbsp 
           <a id="Cancel" href="~/Home/Home"> <input type="button" value="Cancel" id="btncancel" class="button" style="width: 100px;" /></a> 
          </p> 
         </div> 
        </div> 
        @Html.ValidationSummary(true) 
       } 
      </div> 
     </div> 
    </div> 
</div> 
+1

당신은 두 모델이있는 뷰 모델을 가질 수 있고 당신은 당신의보기 –

답변

0

필요한 데이터를 나타내는보기 모델을 사용해야합니다 보기를 렌더링합니다. 뷰 모델에 직접 모델을 노출하거나 (LoD을 위반) 뷰 모델에 대한 호출을 기본 모델에 위임 할 수 있습니다 (DRY 원칙 위반).

+0

씨야 친구와 함께, 내가 @model BloginMVC.Models.PostModel @ { ViewBag.Title = "AddPost"로 모델을 사용하는 것을 결합 할 수있다; 레이아웃 = "~/Views/MasterView/MasterLayout.cshtml"; }하지만 PartialView 즉, 사이드 바의 GET 메서드를 참조하지 않습니다 ... –

+0

"GET 메서드를 참조하지 않습니다"-이게 무슨 뜻인지는 모르겠다. 모델을 부분 모델로 전달하려는 경우 예를 들어 다음과 같이 사용할 수 있습니다. @ Html.Partial ("Sidebar", model.SidebarModel). http://msdn.microsoft.com/en-us/library/ee402926(v=vs.108).aspx – devdigital

+0

단지 두 부분으로 데이터를 표시하기 위해 One View를 사용하고 싶습니다.Left에서 PartialView의 데이터를 표시하고 싶습니다. 하나의 모델을 사용했고 다른 섹션에서 다른 모델을 사용한 sameview의 데이터를 표시하고 싶지만 View가로드되면 ActionResult 메서드가 호출됩니다. 뷰의 GET 유형을 가져 왔지만 PartialView를 렌더링 할 때 Partialview의 GET 유형의 ActionResult 메소드를 호출하지 않으며 부분 뷰에서 사용한 MODEL의 오브젝트 인스턴스에 오브젝트 참조가 설정되지 않은 오류를 제공합니다. –

1

질문이 100 % 이해가되지 않습니다. 그러나 만약 내가 그것을 이해한다면 나는 그것이 당신이 일할 필요가있는 방식으로 작동 할 것이라고 생각하지 않는다 (나는 틀릴 수도있다). 부분 뷰에서 벗어나서 두 섹션을 채우는 데 사용할 수있는 하나의 view model을 전달하는 것이 좋습니다. 보기 모델은보기에서 데이터를 나타냅니다.

시나리오에서 수정하고 사용할 수있는 기본 샘플을 제공 할 예정입니다. 우리는 고객이 있으며이 고객은 1 또는 다수의 주소를 가질 수 있다고 말합니다. 그래서이 두 모델의 기본 표현은 다음과 같이 수 : 당신의 세부 사항에

public class Customer 
{ 
    public int Id { get; set; } 

    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public IEnumerable<Address> Addresses { get; set; } 
} 

public class Address 
{ 
    public int Id { get; set; } 

    public string AddressLine1 { get; set; } 

    public string AddressLine2 { get; set; } 

    public string AddressLine3 { get; set; } 
} 

그리고 지금 당신이 고객의 세부 사항이 고객의 주소를 표시 할 볼 수 있습니다. 따라서 우리는 1 개의보기에 표시 할 2 개의 모델 (고객 및 주소)을 가지고 있습니다.

public ActionResult Details(int id) 
{ 
    Customer customer = customerRepository.GetById(id); 

    if (customer != null) 
    { 
      customer.Addresses = addressRepository.GetAddressesForCustomer(customer.Id); 
    } 

    // The above 2 steps can be done in 1 repository call 

    // Now populate your view model with the above details 
    // This can also be 1 or 2 lines when you use something like Auto Mapper 

    CustomerDetailsViewModel viewModel = new CustomerDetailsViewModel 
    { 
      viewModel.CustomerId = customer.Id, 
      viewModel.CustomerFirstName = customer.FirstName, 
      viewModel.CustomerLastName = customer.LastName, 
      viewModel.CustomerAddresses = customer.Addresses 
    }; 

    return View(viewModel); 
} 

로보기 모델 :

public class CustomerDetailsViewModel 
{ 
    public int CustomerId { get; set; } 

    public string CustomerFirstName { get; set; } 

    public string CustomerLastName { get; set; } 

    public IEnumerable<Address> CustomerAddresses { get; set; } 
} 

그래서 지금 당신은 1 개보기 모델이 개 다른 모델에서 채워 있습니다. 이제이 뷰 모델을 사용하여 데이터를 표시하면됩니다.

@model YourProject.ViewModels.Customers.CustomerDetailsViewModel 

@Model.CustomerId<br /> 
@Model.CustomerFirstName<br /> 
@Model.CustomerLastName<br /><br /> 

@foreach (var address in @Model.CustomerAddresses) 
{ 
    <div> 
      @address.Id<br /> 
      @address.AddressLine1<br /> 
      @address.AddressLine2<br /> 
      @address.AddressLine3<br /> 
    </div> 
} 

이 정보가 도움이되기를 바랍니다.

+0

+1 내가하는 일을 처음으로 잊어 버리십시오. –

+0

고마워요. 브랜든 .. 분명히 저를 도울 것입니다 ... 이제 실제 아이디어를 얻었습니다. –

+0

그런 다음 그것을 수용 대답으로 표시 :) –

관련 문제