Asp.net mvc 排序后webgrid为空
我在局部视图中定义了webgrid。(这是一个MVC4项目。)webgrid不是部分视图中的唯一对象,因此webgrid绑定到部分视图模型中的列表 当单击列标题时,网格会按应有的方式进行填充和排序,但是当我通过调用一个操作方法(通过使用Ajax.BeginForm设置的表单post)重新填充网格,然后单击列标题时,网格内容就会消失。(操作方法使用用户在表单上提供的搜索条件查询数据库。) 这可能是什么原因造成的?如何解决? 局部视图以以下内容开始:Asp.net mvc 排序后webgrid为空,asp.net-mvc,webgrid,Asp.net Mvc,Webgrid,我在局部视图中定义了webgrid。(这是一个MVC4项目。)webgrid不是部分视图中的唯一对象,因此webgrid绑定到部分视图模型中的列表 当单击列标题时,网格会按应有的方式进行填充和排序,但是当我通过调用一个操作方法(通过使用Ajax.BeginForm设置的表单post)重新填充网格,然后单击列标题时,网格内容就会消失。(操作方法使用用户在表单上提供的搜索条件查询数据库。) 这可能是什么原因造成的?如何解决? 局部视图以以下内容开始: @model DonationImport.Mo
@model DonationImport.Models.GiftWithSplits
局部视图的内容在以下指定的表格中:
@using (Ajax.BeginForm("SearchConstit", "Batch", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "constitSearchArea" }))
WebGrid的定义如下:
@{
var constitGrid = new WebGrid(source: Model.SearchResults, rowsPerPage: 100, ajaxUpdateContainerId: "constitGrid");
<div style="overflow-x: scroll; width: 100%;">
<div style="width: 1910px;">
@constitGrid.GetHtml(htmlAttributes: new { id = "constitGrid" },
columns: constitGrid.Columns(
constitGrid.Column(format: @<text><button onclick="selectConstituent('@item.Constituent_ID')" >select</button></text>, style: "searchResultsColumnWidth"),
constitGrid.Column("Constituent_ID", header: "ConstitID", style: "searchResultsColumnWidth", format: @<text>@Html.ActionLink((string)item.Constituent_ID, "PriorGifts", new { constitID = item.Constituent_ID }, new { target = "Prior Payments" })</text>),
constitGrid.Column("IsActive", header: "Active", style: "searchResultsColumnWidth"),
constitGrid.Column("LastName", header: "Last", style: "searchResultsColumnWidth"),
constitGrid.Column("FirstName", header: "First", style: "searchResultsColumnWidth"),
constitGrid.Column("MiddleInitial", header: "M.I.", style: "searchResultsNarrowColumnWidth"),
constitGrid.Column("Spouse", header: "Spouse", style: "searchResultsColumnWidth"),
constitGrid.Column("EmailAddress", header: "E-mail", style: "searchResultsWideColumnWidth"),
constitGrid.Column("AddressLine1", header: "Address Line 1", style: "searchResultsWideColumnWidth"),
constitGrid.Column("City", header: "City", style: "searchResultsWideColumnWidth"),
constitGrid.Column("State", header: "State", style: "searchResultsColumnWidth"),
constitGrid.Column("Zip", header: "Zip", style: "searchResultsWideColumnWidth"),
constitGrid.Column("SearchResultsText", header: "Search Results", style: "searchResultsWideColumnWidth"),
constitGrid.Column("IsActivePledge", header: "Pledge", style: "searchResultsNarrowColumnWidth"),
constitGrid.Column("ReceiptWarning", header: "Receipt Warning", style: "searchResultsWideColumnWidth"),
constitGrid.Column("IsMember", header: "Mbr", style: "searchResultsNarrowColumnWidth")),
alternatingRowStyle: "altrow")
</div>
</div>
}
[HttpPost]
public PartialViewResult SearchConstit(DonationImport.Models.GiftWithSplits g)
{
GiftWithSplits giftWithSplits = new GiftWithSplits(); // model (object) to be returned to the partial view
// send back gift data which we are currently using
giftWithSplits.GiftToVerify = g.GiftToVerify;
// search using provided data
string middleInitial = empty2null(g.GiftToVerify.SourceMiddleName);
if (!string.IsNullOrWhiteSpace(middleInitial))
middleInitial = middleInitial.Substring(0, 1); // just supply the initial, not the entire name
string zip = empty2null(g.GiftToVerify.SourceZip);
if (!String.IsNullOrWhiteSpace(zip))
zip = zip.Substring(0, 5); // we want only the first 5 digits of the zip
giftWithSplits.SearchResults = db.SearchDonor(null, g.GiftToVerify.DonationSourceCode, empty2null(g.SourceAcctMemo), null, empty2null(g.GiftToVerify.SourceLastName),
empty2null(g.GiftToVerify.SourceFirstName), middleInitial, empty2null(g.GiftToVerify.SourceAddress1),
empty2null(g.GiftToVerify.SourceCity), empty2null(g.GiftToVerify.SourceState), zip, empty2null(g.GiftToVerify.SourceCountry),
empty2null(g.GiftToVerify.SourceEmailAddress), empty2null(g.GiftToVerify.SourcePhone)).ToList();
if (giftWithSplits.SearchResults.Count == 0)
{
SearchDonor_Result emptyResult = new SearchDonor_Result();
emptyResult.Constituent_ID = "[None Found]";
giftWithSplits.SearchResults.Add(emptyResult);
}
return PartialView("_ConstitSearch", giftWithSplits);
}
正如您可能知道的,我是这种MVC方法的初学者
其他想法(稍后添加)
问题的根源似乎是WebGrid HTML帮助为列标题生成的链接基于与生成网格的操作方法相关的URL。首次显示网格时,链接为:/Batch/Verify/34?sort=FirstName&sortdir=ASC,因为网格是作为整个验证视图的一部分构建的(来自验证操作方法)。但是,当您搜索手动输入的搜索条件时,网格是从SearchConst操作方法生成的,该方法只填充部分视图,因此列标题链接中的URL现在是:/Batch/SearchConst?sort=FirstName&sortdir=ASC
此外,“搜索”按钮与帖子关联,因为它需要从表单字段传递数据以用作搜索条件;然而,WebGrid列标题使用GET,显然没有办法强制它们发布。因此,问题似乎归结为如何在不发布表单的情况下从表单字段传递搜索条件
我可以想出一个使用会话变量的可能解决方案,但我不太愿意这样做
另一个选择可能是放弃WebGrid的使用
有什么想法吗?当我为同一个问题寻找解决方案时,我找到了你的问题。我也面临同样的问题。我使用web网格来显示数据。 我使用了筛选/分页。我还使用文本框在网格中搜索。 我正在打电话找人。当我点击filter和paging按钮时,Webgrid正在消失。我搜索了很多,没有找到任何解决方案。最后我找到了解决办法,所以想到了发帖。 您需要使用get-ajax调用而不是post调用来解决问题。不要使用beginform post进行搜索
Index.cshtml is my main view. Here i m rendering partial view (_GridPartialView.cshtml). Index view has one webgrid and search text box.
I am using ajax call to search in webgrid. Ajax code is mention below.
**Index.cshtml:**
@model List<Login>
@{
ViewBag.Title = "User";
}
<h2 style="background-color: grey">User</h2>
<table>
<tr>
<td>
<input type="text" id="txtSearch" placeholder=" Search..." onkeyup="Search()" />
@Html.ActionLink("Create New User", "CreateUser")</td>
</tr>
<tr>
<td>
<div id="divPartialView">
@Html.Partial("~/Views/Shared/_GridPartialView.cshtml", Model)
</div>
</td>
</tr>
</table>
<script type="text/javascript">
function Search() {
var searchVal = $("#txtSearch").val();
$.ajax({
type: "GET",
url: '/User/Search',
data: { searchString: searchVal },
dataType: 'html',
success: function (data) {
$('#divPartialView').html(data);
}
});
}
</script>
_GridUserPArtialView.cshtml: This is partial view used in index view.
@model List<Login>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<style type="text/css">
.webGrid { margin: 4px; border-collapse: collapse; width: 500px; background-color:#FCFCFC;}
.header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
.webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
.alt { background-color: #E4E9F5; color: #000; }
.gridHead a:hover {text-decoration:underline;}
.description { width:auto}
.select{background-color: #389DF5}
</style>
@{
var grid = new WebGrid(null, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "grid");
grid.Pager(WebGridPagerModes.NextPrevious);
grid.Bind(Model, autoSortAndPage: true, rowCount: Model.Count);}
<div id="grid">
@grid.GetHtml(
tableStyle: "webGrid", mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("UserName", "User Name", style: "description"),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name"),
grid.Column("Action", format: @<text>
@if (@item.LoginUserName != "administrator"){
@Html.ActionLink("Edit", "Edit", new { id=item.LoginUserName})
@Html.ActionLink("Delete","Delete", new { id = item.LoginUserId},new { onclick = "return confirm('Are you sure you wish to delete this user?');" })
}
</text>, style: "color:Gray;" , canSort: false)
))
</div>
**UserController.cs**: This is Search action method inside. usercontroller. It is HTTPGET.
[HttpGet]
public PartialViewResult Search(string searchString)
{
List<Login> userListCollection = new List<Login_User>();
userListCollection = Login_User_Data.GetAllUsers();
if (Request.IsAjaxRequest())
{
if (!string.IsNullOrEmpty(searchString))
{
Log.Info("UserController: Index() Started");
var searchedlist = (from list in userListCollection
where list.FirstName.IndexOf(searchString,StringComparison.OrdinalIgnoreCase) >=0
|| list.LoginUserName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0
|| list.LastName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0
select list
).ToList();
return PartialView("~/Views/Shared/_GridPartialView.cshtml", searchedlist);
}
else
{
Log.Info("UserController: Search(Login_User user) Ended");
return PartialView("_GridPartialView", userListCollection);
}
}
else
{
return PartialView("_GridPartialView", userListCollection);
}
Log.Info("UserController: Search() Ended");
}
Hope this will help you. Let me know if you have any concern.
From: www.Dotnetmagics.com
Index.cshtml是我的主视图。这里我正在呈现局部视图(_GridPartialView.cshtml)。索引视图有一个webgrid和搜索文本框。
我正在使用ajax调用在webgrid中进行搜索。下面将介绍Ajax代码。
**Index.cshtml:**
@模型列表
@{
ViewBag.Title=“用户”;
}
使用者
@ActionLink(“创建新用户”、“创建用户”)
@Html.Partial(“~/Views/Shared/\u GridPartialView.cshtml”,Model)
函数搜索(){
var searchVal=$(“#txtSearch”).val();
$.ajax({
键入:“获取”,
url:“/User/Search”,
数据:{searchString:searchVal},
数据类型:“html”,
成功:功能(数据){
$('#divPartialView').html(数据);
}
});
}
_GridUserPArtialView.cshtml:这是索引视图中使用的部分视图。
@模型列表
.webGrid{边距:4px;边框折叠:折叠;宽度:500px;背景色:#fcfc;}
.header{背景色:#C1D4E6;字体大小:粗体;颜色:#FFF;}
.webGrid th、.webGrid td{边框:1px实心#c0c0;填充:5px;}
.alt{背景色:#E4E9F5;颜色:#000;}
.gridHead a:悬停{文本装饰:下划线;}
.description{width:auto}
.选择{背景色:#389DF5}
@{
var grid=new WebGrid(null,canPage:true,rowsPerPage:5,selectionFieldName:“selectedRow”,ajaxUpdateContainerId:“grid”);
Pager(WebGridPagerModes.NextPrevious);
Bind(Model,autoSortAndPage:true,rowCount:Model.Count);}
@grid.GetHtml(
表样式:“webGrid”,模式:WebGridPagerModes.All,
第一个文本:“,
lastText:“Last>>”,
headerStyle:“header”,
alternatingRowStyle:“alt”,
selectedRowStyle:“选择”,
列:grid.columns(
grid.Column(“用户名”、“用户名”、样式:“说明”),
网格栏(“名字”、“名字”),
grid.Column(“LastName”、“LastName”),
网格.列(“操作”,格式:@
@如果(@item.LoginUserName!=“管理员”){
@ActionLink(“编辑”,“编辑”,新的{id=item.LoginUserName})
@ActionLink(“Delete”,“Delete”,new{id=item.LoginUserId},new{onclick=“return confirm('您确定要删除此用户吗?');“})
}
,样式:“颜色:灰色;”,canSort:false)
))
**cs**:这是内部的搜索操作方法。用户控制器。这是HTTPGET。
[HttpGet]
公共PartialViewResult搜索(字符串搜索字符串)
{
List userListCollection=新列表();
userListCollection=Login_User_Data.GetAllUsers();
if(Request.IsAjaxRequest())
{
如果(!string.IsNullOrEmpty(searchString))
{
Info(“UserController:Index()已启动”);
var searchedlist=(来自userListCollection中的列表
其中list.FirstName.IndexOf(searchString、StringComparison.OrdinalIgnoreCase)>=0
Index.cshtml is my main view. Here i m rendering partial view (_GridPartialView.cshtml). Index view has one webgrid and search text box.
I am using ajax call to search in webgrid. Ajax code is mention below.
**Index.cshtml:**
@model List<Login>
@{
ViewBag.Title = "User";
}
<h2 style="background-color: grey">User</h2>
<table>
<tr>
<td>
<input type="text" id="txtSearch" placeholder=" Search..." onkeyup="Search()" />
@Html.ActionLink("Create New User", "CreateUser")</td>
</tr>
<tr>
<td>
<div id="divPartialView">
@Html.Partial("~/Views/Shared/_GridPartialView.cshtml", Model)
</div>
</td>
</tr>
</table>
<script type="text/javascript">
function Search() {
var searchVal = $("#txtSearch").val();
$.ajax({
type: "GET",
url: '/User/Search',
data: { searchString: searchVal },
dataType: 'html',
success: function (data) {
$('#divPartialView').html(data);
}
});
}
</script>
_GridUserPArtialView.cshtml: This is partial view used in index view.
@model List<Login>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<style type="text/css">
.webGrid { margin: 4px; border-collapse: collapse; width: 500px; background-color:#FCFCFC;}
.header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
.webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
.alt { background-color: #E4E9F5; color: #000; }
.gridHead a:hover {text-decoration:underline;}
.description { width:auto}
.select{background-color: #389DF5}
</style>
@{
var grid = new WebGrid(null, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "grid");
grid.Pager(WebGridPagerModes.NextPrevious);
grid.Bind(Model, autoSortAndPage: true, rowCount: Model.Count);}
<div id="grid">
@grid.GetHtml(
tableStyle: "webGrid", mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("UserName", "User Name", style: "description"),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name"),
grid.Column("Action", format: @<text>
@if (@item.LoginUserName != "administrator"){
@Html.ActionLink("Edit", "Edit", new { id=item.LoginUserName})
@Html.ActionLink("Delete","Delete", new { id = item.LoginUserId},new { onclick = "return confirm('Are you sure you wish to delete this user?');" })
}
</text>, style: "color:Gray;" , canSort: false)
))
</div>
**UserController.cs**: This is Search action method inside. usercontroller. It is HTTPGET.
[HttpGet]
public PartialViewResult Search(string searchString)
{
List<Login> userListCollection = new List<Login_User>();
userListCollection = Login_User_Data.GetAllUsers();
if (Request.IsAjaxRequest())
{
if (!string.IsNullOrEmpty(searchString))
{
Log.Info("UserController: Index() Started");
var searchedlist = (from list in userListCollection
where list.FirstName.IndexOf(searchString,StringComparison.OrdinalIgnoreCase) >=0
|| list.LoginUserName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0
|| list.LastName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0
select list
).ToList();
return PartialView("~/Views/Shared/_GridPartialView.cshtml", searchedlist);
}
else
{
Log.Info("UserController: Search(Login_User user) Ended");
return PartialView("_GridPartialView", userListCollection);
}
}
else
{
return PartialView("_GridPartialView", userListCollection);
}
Log.Info("UserController: Search() Ended");
}
Hope this will help you. Let me know if you have any concern.
From: www.Dotnetmagics.com
[HttpGet]
public ActionResult YourActionMethod()
{
return PartialView("YourView",YourModel);
}