2014-10-07 40 views
0

我正嘗試使用MVC 4和Razor構建項目。我無法理解部分視圖。我有一個我遍歷的域對象列表,並將它顯示在列表框中(每行都是可點擊的)。我把它分成主視圖和局部視圖,呈現可以正常工作的域對象。在我的部分視圖中,我想使每個項目都可點擊,並且在點擊後,我想創建一個新的局部視圖來顯示有關域對象的詳細信息。部分視圖,重定向到另一個URL?

這裏是我有什麼

我的主要觀點是這樣的

<div class="panely"> 
    <div class="list-group"> 
     @{ Html.RenderPartial("DomainObjectsPartial");} 
     </div> 
</div> 

我的部分觀點是這樣的

<div class="list"> 
    @foreach (var x in @Model) 
    { 
    <a href="@Html.Partial("DomainObjectPartial")" class="list-item"> 
     <em>@x.Name</em> 
    </a> 
    } 
</div> 

我有一個名爲DomainObjectPartial視圖,它有什麼,但與你好的小股利。 當用戶點擊一個域對象上,我期望局部視圖與主視圖中呈現,而是我得到一個錯誤說

從 客戶端檢測到有潛在危險的Request的值( <)。

當我看着我的網址,局部視圖的內容都包含在它像

http://localhost/<div>hello</div> 

我不想被重定向到另一個網址。我只想將部分視圖顯示在列表下方。任何人都可以向我解釋我錯過了什麼或不理解?

回答

1

我猜你想使用AJAX:

<div class="list"> 
    @foreach (var x in Model) 
    { 
     <a href="@Url.Action("Index", "Items", new { id = x.Id })" class="ajax-link"> 
      <em>@x.Name</em> 
     </a> 
    } 
</div> 

,然後你會明顯有一個控制器動作,這將使得該部分:

public class ItemsController: Controller 
{ 
    public ActionResult Index(string id) 
    { 
     // go get the specific item from your database using the id and pass it to 
     // the partial view 
     var viewModel = ... 
     return Partialview("DomainObjectPartial", viewModel); 
    } 
} 

最後一部分,是爲了AJAXify這種定位的:

$(function() { 
    $('.ajax-link').on('click', function() { 
     // Send an AJAX call to the server endpoint pointed by the href attribute 
     // of the anchor and inject the results of this endpoint execution inside a 
     // DOM element with id="result" 
     $('#result').load(this.href); 

     // By returning false you are canceling the default action of the 
     // anchor click and prevent the browser to redirect to the url pointed 
     // by the href property. This would leave enough time for your AJAX request 
     // to execute and return the results. 
     return false; 
    }); 
}); 

並且您顯然需要一個帶有id =「result」的DOM元素我們的頁面包含了AJAX調用的結果:

<div id="result"></div> 
相關問題