首页 > 解决方案 > asp.net mvc Ajax.BeginForm 复制元素

问题描述

我正在使用 ajax 使用局部视图加载数据,同时我已经实现了搜索功能。它工作正常,但是当我将搜索文本框保持为空然后点击搜索按钮时,我的布局就会被复制。
这是我的代码

控制器

     public async Task<ActionResult> Index(string search)
     {
        if (!Request.IsAjaxRequest())
            return View(await _employeeRepository.GetAllEmployeesAsync());

        if (string.IsNullOrEmpty(search))
            return View(await _employeeRepository.GetAllEmployeesAsync());
        return PartialView("_EmployeeList",(await _employeeRepository
            .GetAllEmployeesAsync())
            .Where(x =>x.EmployeeName.StartsWith(search,
                    StringComparison.OrdinalIgnoreCase)));
     }


索引.cshtml

    @model IEnumerable<MvcDemo.Models.Employee>


   @using (Ajax.BeginForm("Index", "Employee", new AjaxOptions
   {
       OnFailure = "record not loaded",
       HttpMethod = "GET",
       UpdateTargetId = "employeeData",
       InsertionMode = InsertionMode.Replace
   }))
   {
      <input type="text" name="search"
        class="form-control"
        placeholder="search by name..."/>

      <input type="submit" value="Search"/>
    }
    <div id="employeeData">
        @Html.Partial("_EmployeeList", Model);
        @* i have used render partial as well*@
    </div>

   @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")
      @Scripts.Render("~/bundles/jqueryajax")
   }


捆绑配置

    bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
            "~/Scripts/jquery.unobtrusive-ajax.min.js"));


布局.cshtml

    @Scripts.Render("~/bundles/jqueryajax")


谁能告诉我哪里出错了?
保持输入空白并单击搜索按钮复制布局。
看看我的屏幕截图
屏幕 1
屏幕 2
屏幕 3
任何帮助将不胜感激。

标签: javascriptc#asp.net-mvcasp.net-mvc-4ajax.beginform

解决方案


如果搜索文本为 null 或为空,您将返回索引视图,而不是此返回部分视图。

if (string.IsNullOrEmpty(search))
    return PartialView("_EmployeeList", (await _employeeRepository.GetAllEmployeesAsync()));

推荐阅读