I want use ajax to prevent refresh my pages and for this I want return Views by PartialView method from controller on ajax call.
问题是:
- 将
View
作为PartialView
返回是一种好方法吗? - 我应该如何在
Controller
的PartialView
方法中设置 View 路径?
例如对于 Views/BasicInfo/_Index 路径中的 _Index View ,我尝试
PartialView("~/Views/BasicInfo/_Index");
,
PartialView("~/Views/BasicInfo/_Index.chtml");
, PartialView("BasicInfo/_Index");
,并得到错误,因为没有找到 View
编辑
如果 View 位于 Shared 文件夹和相关 View 文件夹之外的文件夹中,如何将 View 名称指定到 PartialView 方法中。例如我的 Controller 名称是 controller1 而我的 View 在这个路径 Views/BasicInfo/_Index ?
最佳答案
你应该有这个
我的 Controller
- ActionResult -> 索引
- ActionResult -> IndexPartial
观看次数
- 我的
- Index.cshtml( View )
- IndexPartial.cshtml(局部 View )
- 我的
地点:
作为完整 View 的 Index.cshtml 将使用传递的模型渲染部分 View (为什么这样?以防止代码重复)
@model YourModelType
@{
ViewBag.Title = "View Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.Partial("IndexPartial", Model)
IndexPartial.cshtml 是局部 View ,类似于
@model YourModelType
<h2>Some Title</h2>
<div>
<h4>YourModel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Property1)
</dt>
<dd>
@Html.DisplayFor(model => model.Property1)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Property2)
</dt>
<dd>
@Html.DisplayFor(model => model.Property2)
</dd>
</dl>
现在当你想要完整 View 时使用 MyController/Index,当你想要部分 View 时你可以使用 MyController/IndexPartial
或者您可以在操作上使用参数来指定输出:
public ActionResult GetMyView(bool? partial)
{
var model = something;
if (partial != null && partial)
{
return PartialView("MyViewPartial", model)
}
return View("MyView", model);
}
调用 partial = yourHost/controller/GetMyView?partial=true
现在回到您的问题,是的,您可以将部分 View 返回为 View ,反之亦然。但是您将面临通过 ajax 将 html 附加到页面的问题(不完整或重载的 html)。
关于c# - 通过 PartialView 方法返回 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31267833/