2012-07-31 37 views
0

這可能最終會比我做出來是,一個更簡單的問題,但在這裏不用...ASP.NET C#MVC - 在捕捉的foreach項的值傳遞給模態

我有a BookManager class and a Book class。 BookManager有許多書 - 這是通過使用CodeFirst的EntityFramework設置的。

詳細頁BookManager的的,我使用的是的foreach聲明的鏈接一起顯示書籍的列表編輯特定的書。

下面是代碼:

@foreach (var item in Model.Books) 
    { 

     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.BookName) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.BookNumber) 
      </td> 
      <td>         
       <a class="btn" data-toggle="modal" href="#BookEditModal" @{ViewBag.SelectedBook = item.BookID}> 
       <i class="icon-edit"></i> 
       Edit  
       </a>         

      </td> 
     </tr> 
     } 

這裏是棘手的部分:

<a class="btn" data-toggle="modal" href="#BookEditModal" @{ViewBag.SelectedBook = item.BookID} > 
    <i class="icon-edit"></i> 
     Edit  
</a> 

通常我會做這樣的事情:href="@Url.Action("Edit", "Book", new { id = item.BookID})

不過,我現在用的是HREF屬性打開一個模式窗口,它將使用一個Html.RenderAction顯示來自控制器的適當表格。

這裏是包含在BookManager的詳細信息頁面底部的模態窗口:

<div class="modal hide fade in" id="BookEditModal")> 
      <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal">×</button> 
      <h3>Edit Book</h3> 
      </div> 
      @using (Html.BeginForm("Edit", "Book", FormMethod.Post)) 
      { 
      <div class="modal-body"> 
       @{ Html.RenderAction("Edit", "Book", new { id = ViewBag.SelectedBook}); } 
      </div> 

      } 
     </div> 

因爲我需要在ID通入的RenderAction爲了編輯方法來工作,我需要在foreach中點擊的項目的值 - 但這不在範圍之內。

我試過BookManager的的詳細方法中創建ViewBag.SelectedBook,但爲所選的書,而不是價值,而不是foreach語句遍歷和ViewBag.SelectedBook價值最終被圖書的數量。 (例如,如果我在列表中有3本書,比ViewBag.SelectedBook等於3)。

我想過使用jQuery和調用$上的點擊項目(本),但後來我不得不收集使用JavaScript的BookID和轉換回C#,以收集其在Html.RenderAction - 對於我正在嘗試做的事情來說,這似乎太過分了。

我怎麼會去收集項目的價值點擊並傳遞沿到Html.RenderAction那就是在模態?

謝謝!

回答

2

沒有其他辦法。

我的意思是,你試圖讓服務器端代碼與客戶端腳本進行交互。

由於您的模態對話框在頁面呈現時呈現,您嘗試的內容不起作用。

我的建議,是加載整個模態對話框,通過控制器的動作,或許是這樣的:

生成您的foreach鏈接,就像這樣:

<a class="btn edit-book-link" data-toggle="modal" href="/ControllerName/BookForm/@item.BookID"> 

..make您的模態對話框的div空白,就像這樣:

<div class="modal hide fade in" id="BookEditModal")> 
    <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal">×</button> 
     <h3>Edit Book</h3> 
    </div> 
    <div id="modalContent"></div> 
</div> 

創建一個觀點,即需要一個整數作爲它的模型,叫做,例如,BookForm:

[HttpGet] 
public ViewResult BookForm(int id) { 
    return View(id); 
} 

..then,使用jQuery加載的每次點擊正確的形式:

$(function() { 
    $('.edit-book-link').click(function (e) { 
     $('#modalContent').load($(this).attr('href'), function() { 
      // show your modal dialog here using whatever method you use.. 
     }); 
     e.preventDefault(); 
     return false; 
    }); 
}); 

然後在你的BookForm視圖中,可以使用ID生成表單。

希望我正確理解你的問題。

+0

優雅的解決方案 - 謝謝!我只是將原始圖書編輯表單作爲PartialViewResult返回,而不是製作新表單,而且它的工作方式類似於魅力。 – PhillipKregg 2012-08-01 03:47:59

相關問題