在 ASP.NET MVC 中单击按钮时呈现局部视图 [英] Rendering partial view on button click in ASP.NET MVC

查看:25
本文介绍了在 ASP.NET MVC 中单击按钮时呈现局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将要描述的问题与我已经发现的问题非常相似(例如 这篇文章的名字几乎相同) 但我希望我能把它变成不重复的东西.

我在 Visual Studio 中创建了一个新的 ASP.NET MVC 5 应用程序.然后,我定义了两个模型类:

公共类 SearchCriterionModel{公共字符串关键字{获取;放;}}公共类 SearchResultModel{公共 int Id { 获取;放;}公共字符串名字{获取;放;}公共字符串姓氏 { 获取;放;}}

然后我创建了 SearchController 如下:

公共类 SearchController : 控制器{公共 ActionResult 索引(){返回视图();}公共 ActionResult DisplaySearchResults(){var model = new List{新的 SearchResultModel { Id=1, FirstName="Peter", Surname="Pan" },新的 SearchResultModel { Id=2, FirstName="Jane", Surname="Doe" }};返回 PartialView("SearchResults", 模型);}}

以及视图 Index.cshtml(强类型化,SearchCriterionModel 作为模型和模板 Edit)和 SearchResults.cshtml 作为 部分 视图,模型类型为 IEnumerable(模板 List).

这是索引视图:

@model WebApplication1.Models.SearchCriterionModel@{ViewBag.Title = "索引";}@using (Html.BeginForm()){@Html.AntiForgeryToken()<div class="form-horizo​​ntal"><h4>SearchCriterionModel</h4><小时/>@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 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>@Html.ActionLink("返回列表", "索引")

<div id="搜索结果">

如您所见,我在标准模板下方添加了带有 id="searchResults"div 并编辑了按钮.我想要的是在底部的 div 中显示局部视图 SearchResults.cshtml,但只有在单击按钮之后.我已经通过使用 @Html.Partial("SearchResults", ViewBag.MyData) 成功地在那里显示了一个局部视图,但是它在第一次加载父视图时呈现,我设置了 ViewBag.MyData 已经在 Index() 方法中了,这不是我想要的.

总结:点击按钮时,我将获得一些 SearchResultModel 实例的 List(通过数据库访问),然后应该使用这个新获得的渲染局部视图数据作为模型.我怎样才能做到这一点?我在第一步似乎已经失败了,那就是用上面的代码对按钮点击做出反应.现在,我导航到 URL ~/Search/DisplaySearchResults,但当然那里什么都没有,也没有调用代码隐藏方法.在传统的 ASP.NET 中,我只是添加了一个服务器端 OnClick 处理程序,为网格设置 DataSource 并显示网格.但是在 MVC 中,我已经无法完成这个简单的任务...

更新: 将按钮更改为 @Html.ActionLink 我终于可以进入控制器方法了.但很自然地,因为它返回了部分视图,所以它显示为整个页面内容.所以问题是:如何告诉局部视图在客户端的特定 div 中呈现?

解决方案

将按钮更改为

并添加以下脚本

var url = '@Url.Action("DisplaySearchResults", "Search")';$('#search').click(function() {var keyWord = $('#Keyword').val();$('#searchResults').load(url, { searchText: keyWord });})

并修改控制器方法以接受搜索文本

public ActionResult DisplaySearchResults(string searchText){var model =//基于参数 searchText 构建列表返回 PartialView("SearchResults", 模型);}

jQuery .load 方法调用您的控制器方法,传递搜索文本的值并使用局部视图更新

的内容.

旁注:

标签和 @Html.ValidationSummary()@Html.ValidationMessageFor() 的使用这里可能没有必要.您从不返回 Index 视图,因此 ValidationSummary 没有意义,我假设您希望 null 搜索文本返回所有结果,无论如何您没有属性 Keyword 的任何验证属性,因此无需验证.

编辑

根据 OP 的评论,SearchCriterionModel 将包含多个具有验证属性的属性,然后方法是包含一个提交按钮并处理表单 .submit() 事件

var url = '@Url.Action("DisplaySearchResults", "Search")';$('form').submit(function() {如果 (!$(this).valid()) {返回假;//如果验证错误,则阻止 ajax 调用}var form = $(this).serialize();$('#searchResults').load(url, form);返回假;//阻止默认提交动作})

控制器方法是

public ActionResult DisplaySearchResults(SearchCriterionModel 标准){var model =//根据标准的属性构建列表返回 PartialView("SearchResults", 模型);}

The problem I will be describing is very similar to ones I already found (e.g. this post with nearly identical name) but I hope that I can make it into something that is not a duplicate.

I have created a new ASP.NET MVC 5 application in Visual Studio. Then, I defined two model classes:

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; }
}

Then I created the SearchController as follows:

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);
  }
}

as well as views Index.cshtml (strongly typed with SearchCriterionModel as model and template Edit) and SearchResults.cshtml as a partial view with model of type IEnumerable<SearchResultModel> (template List).

This is the Index view:

@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>

As you can see, I added a div with id="searchResults" below the standard template and edited the button. What I want is to display the partial view SearchResults.cshtml in the div on the bottom, but only after the button is clicked. I have succeeded in showing a partial view there by using @Html.Partial("SearchResults", ViewBag.MyData), but it is rendered when the parent view is loaded for the first time and I set ViewBag.MyData in the Index() method already, which is not what I want.

Summary: On clicking the button, I will obtain some List of SearchResultModel instances (via database access) and then the partial view should be rendered, using this newly obtained data as model. How can I accomplish this? I already seem fail at the first step, that is reacting to the button click with the above code. Right now, I navigate to the URL ~/Search/DisplaySearchResults, but of course there's nothing there and no code-behind method is called. In traditional ASP.NET I'd just have added a server-side OnClick handler, set the DataSource for a grid and show the grid. But in MVC I already fail with this simple task...

Update: Changing the button to @Html.ActionLink I can finally enter the controller method. But naturally since it returns the partial view, it's displayed as the whole page content. So the question is: How do I tell the partial view to be rendered inside a specific div on the client side?

解决方案

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

这篇关于在 ASP.NET MVC 中单击按钮时呈现局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆