Reputation: 571
I am using ajax to load data using partial view and at the same i have implemented search functionality. Its working fine but when i keep my search textbox empty and then hit search button then my layout gets duplicated.
here is my code
controller :
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)));
}
Index.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")
}
BundleConfig:
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js"));
Layout.cshtml :
@Scripts.Render("~/bundles/jqueryajax")
Can anybody tell me where i am going wrong ?
Keeping the input blank and clicking on search button duplicating the layout.
Take a look at my screenshot
screen 1
screen 2
screen 3
Any help would be much appreciated.
Upvotes: 1
Views: 325
Reputation: 375
If search text is null or empty, you are returning the index view, instead of this return partial view.
if (string.IsNullOrEmpty(search))
return PartialView("_EmployeeList", (await _employeeRepository.GetAllEmployeesAsync()));
Upvotes: 1