部分视图,重定向到另一个URL?

时间:2014-10-07 20:25:34

标签: asp.net-mvc razor partial-views

我正在尝试使用MVC 4和Razor构建项目。我无法理解部分观点。我有一个我遍历的域对象列表,并在列表框中显示(每行都是可点击的)。我将其拆分为主视图和局部视图,使得域对象可以正常工作。在我的局部视图中,我想让每个项目都可点击,点击后,我想创建一个新的局部视图,显示有关域对象的详细信息。

这就是我所拥有的

我的主视图看起来像这样

<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的视图,它只有一个带有hello的小div。 当用户点击域对象时,我希望部分视图在主视图中呈现,但我得到一个错误说

  

从中检测到潜在危险的Request.Path值   客户(&lt;)。

当我查看我的网址时,部分视图的内容就像

一样包含在其中
http://localhost/<div>hello</div>

我不想被重定向到另一个网址。我只想将部分视图显示在列表下方。谁能向我解释我缺少什么或不理解?

1 个答案:

答案 0 :(得分: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>