【发布时间】:2015-05-22 10:32:40
【问题描述】:
我将要描述的问题与我已经发现的问题非常相似(例如this post with nearly identical name),但我希望我可以将其变成不重复的问题。
我在 Visual Studio 中创建了一个新的 ASP.NET MVC 5 应用程序。然后,我定义了两个模型类:
public class SearchCriterionModel
{
public string Keyword { get; set; }
}
public class SearchResultModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
然后我创建了SearchController,如下所示:
public class SearchController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DisplaySearchResults()
{
var model = new List<SearchResultModel>
{
new SearchResultModel { Id=1, FirstName="Peter", Surname="Pan" },
new SearchResultModel { Id=2, FirstName="Jane", Surname="Doe" }
};
return PartialView("SearchResults", model);
}
}
以及视图Index.cshtml(强烈键入SearchCriterionModel作为模型和模板编辑)和SearchResults.cshtml作为@类型模型的部分视图987654328@(模板列表)。
这是索引视图:
@model WebApplication1.Models.SearchCriterionModel
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SearchCriterionModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Keyword, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Keyword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Keyword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="btnDisplaySearchResults" value="Search" onclick="location.href='@Url.Action("DisplaySearchResults", "SearchController")'" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="searchResults">
</div>
如您所见,我在标准模板下方添加了div 和id="searchResults",并编辑了按钮。我想要的是在底部的div 中显示部分视图SearchResults.cshtml,但只有在单击按钮之后。我已经通过使用@Html.Partial("SearchResults", ViewBag.MyData) 成功地在那里显示了部分视图,但是它是在第一次加载父视图时呈现的,并且我已经在Index() 方法中设置了ViewBag.MyData,这不是我想要的。
总结:点击按钮后,我将获得一些List 的SearchResultModel 实例(通过数据库访问),然后应该渲染部分视图,使用这个新获得的数据作为模型。 我怎样才能做到这一点?我似乎已经在第一步失败了,即使用上面的代码对按钮单击做出反应。现在,我导航到 URL ~/Search/DisplaySearchResults,当然那里什么都没有,也没有调用任何代码隐藏方法。
在传统的 ASP.NET 中,我只需添加一个服务器端 OnClick 处理程序,为网格设置 DataSource 并显示网格。但是在 MVC 中,我已经在这个简单的任务上失败了......
更新: 把按钮改成@Html.ActionLink 终于可以进入控制器方法了。但自然因为它返回的是部分视图,所以它显示为整个页面内容。所以问题是:如何告诉要在客户端的特定div 内呈现部分视图?
【问题讨论】:
-
通常,您处理按钮单击事件并使用 ajax 将搜索文本传递给返回部分视图的控制器方法,然后使用返回的结果更新 DOM。查看 jquery
ajax()或load()方法。 -
我会用你需要的整个 HTML 为你的 DisplaySearchResults 操作创建新视图,并在索引视图中删除这个 serchResult div。它应该可以工作,但之后我会创建一些部分并重构这两个视图(索引和 DisplaySearchResults),因为代码重复
标签: c# jquery asp.net-mvc