c# - 在 ASP.NET MVC 中单击按钮时呈现局部 View

标签 c# jquery asp.net-mvc

我将要描述的问题与我已经发现的问题(例如 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作为模型类型为 部分 的 View IEnumerable<SearchResultModel> (模板列表)。

这是索引 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>

如您所见,我添加了一个 divid="searchResults"在标准模板下方并编辑按钮。我想要的是显示局部 View SearchResults.cshtmldiv在底部,但仅在单击按钮后。我已经通过使用 @Html.Partial("SearchResults", ViewBag.MyData) 成功地显示了部分 View 。 , 但它是在第一次加载父 View 时呈现的,我设置了 ViewBag.MyDataIndex()方法已经存在,这不是我想要的。

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

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

最佳答案

把按钮改成

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

并添加以下脚本

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

并修改 Controller 方法以接受搜索文本

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

jQuery .load方法调用您的 Controller 方法,传递搜索文本的值并更新 <div> 的内容部分 View 。

旁注:<form> 的使用标记和 @Html.ValidationSummary()@Html.ValidationMessageFor()这里可能没有必要。你永远不会返回 Index这么看ValidationSummary没有意义,我假设你想要一个 null搜索文本以返回所有结果,无论如何您都没有属性 Keyword 的任何验证属性所以没有什么可验证的。

编辑

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

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

Controller 方法是

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

关于c# - 在 ASP.NET MVC 中单击按钮时呈现局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142422/

相关文章:

c# - c#中的可选参数

javascript - jquery过滤掉特定元素

c# - 将值传递给 Controller ​​操作

c# - 发送异步电子邮件

c# - 使用 Xamarin.Forms 和 Zxing 生成二维码

c# - 在 C# 中创建包含对象的数组

c# - LinkedIn Oauth - 从 C# 撤销访问

jquery - 如何使用 Bootstrap 构建自定义工具提示窗口?

jquery - IE 6/7/8 浏览器的奇怪浏览器兼容性问题

.net - 创建与 ASPNetUsers 表和自定义的关系