2017-12-05 3 views
0

/Home/Index에 표시되는 Search.cshtml이라는 부분 뷰가 있습니다. 이 파일에는 검색 결과와 함께/Views/Accounts/Index를 검색하고 끌어 오는 HTML 양식이 있습니다. 그 결과를 검색보기에있는 모달 팝업 div에 표시하려고합니다.모달 팝업에서 부분보기 표시

아래 코드에서 Search (sumbit 입력)를 클릭하면 빈 모달이됩니다.

MVC에 관해서는 아직 초보자입니다. Stack Overflow에서 찾은 몇 가지 다른 결과를 시도했지만 해상도를 찾을 수 없었습니다. 아래 코드는 적어도 공백이지만 모달 팝업을 제공합니다.

나는 미친 듯이 뭔가를 놓치고 있습니까? 아래 모달 - 몸 (Html.Action, RenderAction, 부분, RenderPartial) 모든 것을 시도하고 아무것도 작동하는 것. 또한 나는 거기에 잘못된 나무를 짖고 있습니까?

아래에 몇 개의 스크린 샷과 코드가 있습니다. 이 점을 이해하는 데 도움이 될만한 사항이 있으면 감사하겠습니다. 고맙습니다.

/Home/Index with Search partial view

Empty Search Modal

Search.cshtml

@model CustomerRelationshipManager.Models.Search 

@{ViewBag.Title = "Search";} 
@using (Html.BeginForm("Index", "Accounts", new { id = "searchForm" })) 
{ 

<div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px; 
    width: 325px; margin: auto; display: table;"> 
    <table> 
     <tr> 
      <td valign="top"> 
       Search By: 
      </td> 
      <td> 
       @Html.DropDownList("Search_Type", "Search_Type") 
      </td> 
     </tr> 
     <tr> 
      <td valign="top"></td> 
      <td> 
       @Html.TextBox("Search_String") 
      </td> 
     </tr> 
     <tr> 
      <td></td> 
      <td> 
       <input type="submit" data-toggle="modal" data-target="#myModal" value="Search" /> 
      </td> 
     </tr> 
    </table> 
</div> 

<div class="modal fade" id="myModal"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
       <h4 class="modal-title">Modal title</h4> 
      </div> 
      <div class="modal-body"> 
       @{Html.Action("Index","Accounts");} 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
       <button type="button" class="btn btn-primary">Save changes</button> 
      </div> 
     </div><!-- /.modal-content --> 
    </div><!-- /.modal-dialog --> 
</div><!-- /.modal --> 

}

HomeController.cs

public ActionResult Search() 
    { 
     List<SelectListItem> items = new List<SelectListItem>(); 
     items.Add(new SelectListItem() { Text = "Account Number", Value = "Account_ID" }); 
     items.Add(new SelectListItem() { Text = "Last Name", Value = "Last_Name" }); 
     items.Add(new SelectListItem() { Text = "Phone Number", Value = "Phone_Number" }); 
     ViewBag.Search_Type = items; 
     return PartialView(); 
    } 

    [HttpPost] 
    [AllowAnonymous] 
    public ActionResult Search(Search search) 
    { 

     return PartialView("~/Accounts/Index"); 
     //return RedirectToAction("Index", "Accounts"); 
    } 

AccountController.cs는

@model IEnumerable<CustomerRelationshipManager.Models.Account> 

@{ 
ViewBag.Title = "Home"; 
} 

<h2>Index</h2> 

<p> 
@Html.ActionLink("Create New", "Create") 
</p> 
<table class="table"> 
<tr> 
    <th>Account #</th> 
    <th>Contact Name(s)</th> 
    <th>Address</th> 
    <th>Contact</th> 
</tr> 
w2 
@foreach (var item in Model) 
{ 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Account_ID) 
      <span>&nbsp;</span> 
     </td> 
     <td> 
      @foreach (var i in item.Account_Person) 
      { 
       <span> 
        <b>@Html.DisplayFor(x => i.Person_Type.Name)</b> 
        <br /> 
        @Html.DisplayFor(x => i.Person.First_Name) 
        &nbsp; 
        @Html.DisplayFor(x => i.Person.Last_Name) 
       </span> 
       <br /> 
      } 
     </td> 
     <td> 
      @foreach (var i in item.Account_Address) 
      { 
       <span> 
        <b>@Html.DisplayFor(x => i.Address_Type.Name)</b> 
        <br /> 
        @Html.DisplayFor(x => i.Address.Address1) 
        <br /> 
        @Html.DisplayFor(x => i.Address.Address2) 
        @if (i.Address.Address2 != null) 
        { <br />} 
        @Html.DisplayFor(x => i.Address.City) 
        &nbsp; 
        @Html.DisplayFor(x => i.Address.State) 
        &nbsp; 
        @Html.DisplayFor(x => i.Address.Postal_Code) 
        <br /> 
        @Html.DisplayFor(x => i.Address.Country) 
        <br /> 
       </span> 
      } 
     </td> 
     <td> 
      @foreach (var i in item.Account_Contact) 
      { 
       <span> 
        <b>@Html.DisplayFor(x => i.Contact.Contact_Type.Name)</b> 
        <br /> 
        @Html.DisplayFor(x => i.Contact.Value) 
        <br /> 
       </span> 

      } 

     </td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new { id = item.Account_ID }) | 
      @Html.ActionLink("Details", "Details", new { id = item.Account_ID }) | 
      @Html.ActionLink("Delete", "Delete", new { id = item.Account_ID }) 
     </td> 
    </tr> 
} 

+1

제출 버튼이 양식 태그 안에 있으면 양식 제출을 클릭하여 제출하십시오. 부분 뷰 결과를 얻고 모달 내용을 업데이트하려면 action 메소드에 대한 ajax 호출을 작성해야합니다. – Shyju

답변

0

으로 (내가 모달 팝업이를 표시 할)

public ActionResult Index(string Search_Type, string Search_String) 
    { 
     if (Search_String == null) 
     { 
      var accounts = db.Accounts 
       .Include(a => a.Account_Type) 
       .Include(a => a.Account_Person) 
       .Include(a => a.Account_Address) 
       .Include(a => a.Account_Contact); 
      return PartialView(accounts.ToList()); 
     } 
     else 
     { 
      if (Search_Type == "Account_ID") 
      { 
       var accounts = db.Accounts 
       .Include(a => a.Account_Type) 
       .Include(a => a.Account_Person) 
       .Include(a => a.Account_Address) 
       .Include(a => a.Account_Contact) 
       .Where(a => a.Account_ID.ToString() == Search_String); 
       return PartialView(accounts.ToList()); 
      } 
      else if (Search_Type == "Last_Name") 
      { 
       var accounts = db.Accounts 
       .Include(a => a.Account_Type) 
       .Include(a => a.Account_Person) 
       .Where(b => b.Account_Person.Any(c => c.Person.Last_Name.StartsWith(Search_String))) 
       .Include(a => a.Account_Contact) 
       .Include(a => a.Account_Address); 
       return PartialView(accounts.ToList()); 
      } 
      else if (Search_Type == "Phone_Number") 
      { 
       var accounts = db.Accounts 
       .Include(a => a.Account_Type) 
       .Include(a => a.Account_Person) 
       .Include(a => a.Account_Contact) 
       .Where(b => b.Account_Contact.Any(c => c.Contact.Value == Search_String && c.Contact.Contact_Type.Name.Contains("Phone"))) 
       .Include(a => a.Account_Address); 
       return PartialView(accounts.ToList()); 
      } 
      else 
      { 
       var accounts = db.Accounts 
        .Include(a => a.Account_Type) 
        .Include(a => a.Account_Person) 
        .Include(a => a.Account_Address) 
        .Include(a => a.Account_Contact); 
       return PartialView(accounts.ToList()); 
      } 
     } 

계정 Index.cshtml을 (나는이 컨트롤러에서 색인()를 호출 할) 현재 코드, 사용자가 제출 버튼을 클릭하면 제출 버튼이 form 태그 안에 있으므로 정상적인 양식 제출을 수행합니다. 유스 케이스의 경우 일반 형식 submit 이벤트를 javascript를 사용하여 하이재킹하고 액션 메소드에 ajax 호출을 수행하여 search_typesearch_string 매개 변수를 사용하여 필터링 된 데이터를 가져오고 부분보기 결과를 반환해야합니다. 이 부분보기 결과는 모달 대화 상자에 표시하려는 HTML 마크 업입니다. Ajax 호출이 서버로부터 응답을 받으면이 응답으로 모달 대화 상자의 본문 내용을 업데이트하고 모달 대화 상자를 시작합니다.

@using (Html.BeginForm("Index", "Accounts", FormMethod.Post, new { id = "searchForm" })) 
{ 
    <div> 
     <input type="text" name="Search_String" /> 
     <input type="submit" id="submit" value="Search" /> 
    </div> 
}  
<div class="modal fade" id="myModal"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" 
             data-dismiss="modal" aria-label="Close"> 
        <span aria-hidden="true">&times;</span> 
       </button> 
       <h4 class="modal-title">Modal title</h4> 
      </div> 
      <div class="modal-body"> 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn" data-dismiss="modal">Close</button> 
       <button type="button" class="btn btn-primary">Save changes</button> 
      </div> 
     </div><!-- /.modal-content --> 
    </div><!-- /.modal-dialog --> 
</div><!-- /.modal --> 

은 이제 검색 폼에 제출 이벤트를 수신 일부 자바 스크립트 코드를 가지고 (제출 일반 양식) 정상적인 행동을 중지하고 대신 아약스 양식을 제출하나요합니다.

$(document).ready(function() { 

    $('#searchForm').submit(function (e) { 
     e.preventDefault(); 
     var $form = $(this); 

     $.post($form.attr("action"), $form.serialize()).done(function (res) { 
      $mymodal = $("#myModal"); 
      //update the modal's body with the response received 
      $mymodal.find("div.modal-body").html(res); 
      // Show the modal 
      $mymodal.modal("show"); 
     }); 
    }); 

}); 

이제 당신은 (그것이 어떤 레이아웃 코드를 실행하지만, 그냥보기 코드하지 않도록) 귀하의 색인 작업 방법은 부분 뷰를 반환 있는지 확인해야합니다.

[HttpPost] 
public ActionResult Index(string Search_Type, string Search_String) 
{ 
    // Your existing filtering code goes here. 
    return PartialView(accounts.ToList()); 
} 
+0

안녕하세요, 위 코드를 추가했지만 제대로 작동하지 않는 것 같습니다. 내가 가진 첫 번째 오류는 $ 정의되지 않았습니다. 이 코드는 _layout.cshtml에 JS 코드를 추가해야했기 때문에 발생했습니다.이 코드가 종속되어있는 스크립트가 거기에로드 되었기 때문입니다. 지금 당장 비어있는 모달 팝업으로 시작한 곳으로 돌아 왔습니다. – Nyhack56

+0

즉, jQuery가 페이지에 포함되기 전에 jQuery를 사용하고 있음을 의미합니다. 페이지의 뷰 소스를 확인하고 jQuery 라이브러리와'$'를 사용하는 행의 순서를 확인하십시오. 'scripts' 섹션을 사용하여 페이지 레벨 스크립트를 포함시켜 jQuery가 페이지에 포함 된 후에 실행되도록 할 수 있습니다. 이것을 참조하십시오. jquery가 잘 작동하도록 mvc 응용 프로그램에 js 스크립트 파일을 어디에 배치해야합니까?] (https://stackoverflow.com/questions/34147155/where-should-i-place-the-js-script-files- in-a-mvc-application-so-jquery-works-we/34147263 # 34147263) – Shyju

0

나는 그것을 알아 냈다!

  1. 모달을 Search.cshtml의 HTML.BeginForm 외부로 옮겼습니다. 그런 다음 양식의 입력을 단순화하고 데이터 토글 및 데이터 대상 속성을 제거했습니다.

  2. @model CustomerRelationshipManager.Models.Search 
    
    @{ 
        ViewBag.Title = "Search"; 
    } 
    @using (Html.BeginForm("Index", "Accounts", FormMethod.Post, new { id = "searchForm" })) 
    { 
    
    <div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px; 
    width: 325px; margin: auto; display: table;"> 
        <table> 
        <tr> 
         <td valign="top"> 
          Search By: 
         </td> 
         <td> 
          @Html.DropDownList("Search_Type", "Search_Type") 
         </td> 
        </tr> 
        <tr> 
         <td valign="top"></td> 
         <td> 
          @Html.TextBox("Search_String") 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <input type="submit" id="submit" value="Search" /> 
         </td> 
        </tr> 
    </table> 
    </div> 
    } 
    <div class="modal fade" id="myModal"> 
        <div class="modal-dialog"> 
        <div class="modal-content"> 
         <div class="modal-header"> 
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
          <h4 class="modal-title">Modal</h4> 
         </div> 
         <div class="modal-body"> 
    
         </div> 
         <div class="modal-footer"> 
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
          <button type="button" class="btn btn-primary">Save changes</button> 
         </div> 
        </div><!-- /.modal-content --> 
    </div><!-- /.modal-dialog --> 
    

    은 내가 _layout.cshtml 공유 파일의 맨 아래에 자바 스크립트를 옮겼습니다.

    @Scripts.Render("~/bundles/jquery") 
    @Scripts.Render("~/bundles/bootstrap") 
    @RenderSection("scripts", required: false) 
    
    <script type="text/javascript"> 
    $(document).ready(function() {    
        $('#searchForm').submit(function (e) { 
         e.preventDefault(); 
         var $form = $(this); 
         $.post($form.attr("action"), $form.serialize()).done(function (res) { 
          $mymodal = $("#myModal"); 
          //update the modal's body with the response received 
          $mymodal.find("div.modal-body").html(res); 
          // Show the modal 
          $mymodal.modal("show"); 
         }); 
        }); 
    
        }); 
    
  3. 것을 파악 후, 나는 내 AccountsController의 지수() 함수에 중단 점을 설정하여 발견 된 LINQ 오류가 있었다. 일단 그것을 고치면 내 AccountsController의 Index() Action이 Modal Popup에 나타납니다. 당신의 도움, Shyju에 대한

HomeController Search() Modal Dialog Displaying AccountsController Index()

감사합니다!

관련 문제