MVC: Ajax Webgrid of Partial view paging and sorting - ajax

In my partial view I have upload document and ajax webgrid which displays the document that is uploaded.
This is my partial view Upload_doc.cshtml,
#{
WebGrid doc_upload = new WebGrid(null, rowsPerPage: 5, fieldNamePrefix: "g1", pageFieldName: "p1",
ajaxUpdateContainerId: "grid");
doc_upload.Bind(Model.documents, autoSortAndPage: true, rowCount: 5);
}
<div id="ajaxgrid">
<input type="file" id="file" name="file" />
<input type="submit" class="btn btn-warning"/>
<div >
#doc_upload.GetHtml(htmlAttributes: new { id = "grid" }, tableStyle: "table table-bordered", mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>", columns: doc_upload.Columns(
doc_upload.Column("sno", "Serial No.", canSort: true),
doc_upload.Column("docdesc", "Document Title"),
doc_upload.Column("docdt", "Document Date", format: (k) => k.docdt != null ? string.Format("{0:dd-MMM-yyyy}", k.docdt) : ""),
doc_upload.Column(header: "Actions", format: (item) =>
new HtmlString(
Html.ActionLink("View", "ViewDoc", new { sno=item.sno}, new { target = "_blank" }) + " " +
Ajax.ActionLink("Delete", "delete",
new { sno=item.sno }, new AjaxOptions
{
UpdateTargetId = "test",
InsertionMode = InsertionMode.Replace
})
)
)
))
</div>
My problem is:-
case(i) When I click on header to sort, whole page does postback as it excutes Index page and same for paging defeating the purpose of ajax.
case (ii) If I upload document and then I sort or do paging, my webgrid disappears.
case(iii) If I delete a document and then I sort or do paging, it will execute delete function again.
So, How to change default loading page of web grid?
Please Help!!! Thank You

Related

Pagination on WebGrid deactivates after adding entries

I'm using a WebGrid with pagination in conjunction with an AJAX popup window to add new entries. I've noticed that after I've added an entry the pagination links at the bottom of the WebGrid become inactive.
The popup calls the controller's Save action which finishes with the following:
return PartialView("_PersonGrid", pModel.Persons);
There are three views that are used here. An index, a grid and a popup. The grid is embedded in the index and the popup can be called by clicking on buttons on the grid and index.
The index view has the following code:
#using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myUserGrid" }))
{
<div id="myUserGrid">
#Html.Partial("_PersonGrid", Model.Persons)
</div>
<br />
//other code
}
The grid view (_PersonGrid.cshtml) is:
#model IEnumerable<CIMsWebApp.Client.Group.Entities.IPerson>
#{ var grid = new WebGrid(Model, canSort: true, canPage: true, defaultSort: "UserName", ajaxUpdateContainerId: "myUserGrid"); }
#grid.GetHtml(
tableStyle: "dataGrid",
headerStyle: "header",
alternatingRowStyle: "evenRow",
columns: grid.Columns
(
grid.Column(header: "User Name", columnName: "UserName", format: item => Html.Raw("<a href='#' class='userNames' data-personid='"+item.PersonId+"'>" + item.UserName + "</a>"), canSort: false),
grid.Column(header: "Role(s)", columnName: "Rolebuilder", canSort: false),
grid.Column(header: "Active", columnName: "ActiveIndBuilder", canSort: false),
grid.Column(header: "Action", format:
#<span><input type="button" class="edit-user" id="#item.PersonId" value="EDIT" />
</span>, canSort: false)
)
)
finally the popup view is:
#model CIMsWebApp.Models.PersonModel
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { id = "formUser" }))
{
//code
}
When I first arrive at the page or If I refresh it they become active again.
I'm guessing your "ajaxUpdateContainerId: "myUserGrid"" is a div with an id="myUserGrid" and the partial is loaded in there.. So correct me if I'm wrong but I believe that div should be in your partial. It's a bit confusing sometimes but you should try this out..
View:
#*Everything else except the div*#
#{Html.RenderPartial("_PersonGrid", Model)
PartialView:
#model IEnumerable<CIMsWebApp.Client.Group.Entities.IPerson>
<div id="myUserGrid">
#{ var grid = new WebGrid(Model, canSort: true, canPage: true, defaultSort: "UserName", ajaxUpdateContainerId: "myUserGrid"); }
#grid.GetHtml(
tableStyle: "dataGrid",
headerStyle: "header",
alternatingRowStyle: "evenRow",
columns: grid.Columns
(
grid.Column(header: "User Name", columnName: "UserName", format: item => Html.Raw("<a href='#' class='userNames' data-personid='"+item.PersonId+"'>" + item.UserName + "</a>"), canSort: false),
grid.Column(header: "Role(s)", columnName: "Rolebuilder", canSort: false),
grid.Column(header: "Active", columnName: "ActiveIndBuilder", canSort: false),
grid.Column(header: "Action", format:
#<span><input type="button" class="edit-user" id="#item.PersonId" value="EDIT" />
</span>, canSort: false)
)
)
</div>
If this doesn't work, give some additional data (the view in which you call the partial, where and how you call the save action, etc...)
After looking into how the WebGrid pagination actually works it seems that after carrying out a save it then tries to call a GET method on the Save method. So I created a method for this very purpose and then redirected it back to the Index method. The final two parameters get passed directly to the query string which are then used in the pagination.
[ActionName("Save")]
public ActionResult Pagination(string page, string __, long id = 0)
{
return RedirectToAction("Index", new {id = id, page=page, __ = __ });
}

webgrid selected row MVC 3

I have 2 WebGrid. I want to use the property SelectedRow. in the first WebGrid works well, but the second not.
This is the main view (WebGrid 1), here called a partial view that contains the second WebGrid:
#model IEnumerable<RolesMVC3.Models.ESTUDENT>
#{
ViewBag.Title = "Index";
WebGrid grid = new WebGrid(Model);
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(fillEmptyRows: false,
alternatingRowStyle: "alternate",
headerStyle: "header",
tableStyle: "table",
selectedRowStyle: "selected",
mode: WebGridPagerModes.All,
columns: new[] {
grid.Column("IdEstudent", header: "ID"),
grid.Column("NameEstudent", header: "Name"),
grid.Column("LastNameEstudeNT", header: "Last Name"),
grid.Column( "", header: " ",format:#<text>#item.GetSelectLink("SELECT")</text>)
})
if (grid.HasSelection)
{
Html.RenderAction("Process", "Pass", new { id = grid.SelectedRow["IdEstudent"] });
}
}
This is a partial view of the second WebGrid (WebGrid 2). The WebGrid 2 contains records, but Why grid2.SelectedRow ["IdConsultation"] is NULL?
**Process.cshtml:**
#model IEnumerable<RolesMVC3.Areas.Manager.Models.ConsViewModel>
#{
WebGrid grid2 = new WebGrid(Model);
}
#grid2.GetHtml( fillEmptyRows: false,
alternatingRowStyle: "alternate",
headerStyle: "header",
tableStyle : "table",
selectedRowStyle: "selected",
mode: WebGridPagerModes.All,
columns: new [] {
grid2.Column("IdConsultation", header: "Consultation"),
grid2.Column("Idregister", header: "Register"),
grid2.Column( "", header: " ",format:#<text>#item.GetSelectLink("SELECT")</text>)
})
#if (grid2.HasSelection)
{
<input type="hidden" id="Consultation" name="Consultation" value="#grid2.SelectedRow["IdConsultation"]"/>
Html.RenderAction("EstudianiatesCJ1", "Sustitucion");
}
blessings
grid2.SelectedRow ["IdConsultation"] is NULL because nothing is selected. You should set the first row selected by default if you want so.
im currently using the selection by Javascript with the following JS code:
$(document).on('click', '#selectBtn', function () {
var tr = $(this).closest('tr');
tr.addClass('info').siblings().removeClass('info');
/*Here you can send selection to controller */
return false;
});
Hope this help!

ASP.NET MVC3: WebGrid + Ajax Filters + Ajax Sorting & Paging

Basically, I'm using WebGrid and I need to filter the results. The first problem I have here is it's my first time using WebGrid and I was hoping some of you could give me a hand with it... So far, I've managed to sort grid results and filter them with Ajax, but, when re-sorting the filtered results, the subset is lost and I go back to the beginning with the full set of results. I know why it's happening of course, but I don't figure out how to make it work.
Example:
On my view:
#model IQueryable<Cities>
#section MoreScripts
{
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
}
#using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "GridData"}))
{
<fieldset>
<legend>Search Filters</legend>
<br />
<div>
Name
</div>
<div>
#Html.TextBox("Name")
</div>
<p>
<input type="submit" value="Search" />
</p>
</fieldset>
}
<div id="GridData">
#Html.Partial("Grid", Model)
</div>
My Partial View:
#model IQueryable<Cities>
#{
var grid = new WebGrid<Cities>(null,rowsPerPage: 5, defaultSort: "Nombre", ajaxUpdateContainerId: "GridData");
grid.Bind(Model, autoSortAndPage: true, rowCount: Model.Count());
#grid.GetHtml(columns:
grid.Columns(
grid.Column("Name", "Name", canSort: true),
grid.Column("CreationDate", "Creation Date", canSort: true),
grid.Column("Active", "Active", canSort: true, format: #<text><input type="checkbox" disabled="disabled" value="#item.ID" #(item.Active == true ? "Checked" : null) /></text>),
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { #class = "editLink smallCell", #title = "Edit" })),
grid.Column(format: (item) => Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { #class = "deleteLink smallCell", #title = "Delete" }))),
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style");
}
And finally what am doing wrong is here, on my controller:
public ActionResult Index()
{
return View(repository.GetAllRecords().OrderByDescending(f => f.CreationDate));
}
[HttpPost]
public ActionResult Index(string name)
{
var data = repository.GetAllRecords();
if(!string.IsNullOrEmpty(name))
data = data.Where(a => a.Name.Contains(name));
data = data.OrderByDescending(f => f.CreationDate);
return PartialView("Grid", data);
}
I'm also using a class WebGrid : WebGrid as seen here:
http://archive.msdn.microsoft.com/mag201107WebGrid/Release/ProjectReleases.aspx?ReleaseId=5667
So, this actually works fine for filtering, but once you get the filtered results and then try to change the sort order of your narrowed search results, you lose the elements and the 'name' parameter's value because the WebGrid goes agains the first controller action. Probably this is not the best approach, but as I said, I've never used WebGrid so I'm willing to learn. Any help would be really appreciated. Thanks.
Try to add FormMethod.Post to your form, so the request will go to the second ActionResult. Otherwise, the request is a GET, and goes to the first ActionResult Index() without the parameters.

Razor webgrid sorting not working if grid is loaded using ajax

This is my code
WebGrid passiveAdGrid = new WebGrid(Model.InactiveAds, rowsPerPage: 10, ajaxUpdateContainerId: "passiveAdGrid");
<div >
#passiveAdGrid.Pager(WebGridPagerModes.NextPrevious);
#passiveAdGrid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
htmlAttributes: new { id = "passiveAdGrid" },
columns: passiveAdGrid.Columns(
passiveAdGrid.Column(format: #<text><img src="#Url.Content("~/Content/images/preview-photo.gif")" alt="Image"/></text>),
passiveAdGrid.Column("Title", "Title", canSort: true),
passiveAdGrid.Column("ExpirationDate", "Date of Expiry", canSort: true),
passiveAdGrid.Column("NumViews", "Number of views", canSort: true),
passiveAdGrid.Column(format: (item) => Html.ActionLink("Activate", "PostAd", "Ads", new { relist = item.Id }, null)),
passiveAdGrid.Column(format: (item) => #Ajax.ActionLink("Remove", "RemoveAd", "Ads", new { adID = item.Id, status = "ActivationPending" }, new AjaxOptions { UpdateTargetId = "AdView", HttpMethod = "POST", OnBegin = "return confirm('Are you sure you wish to delete this Ad?');" }))
));
</div>
its works fine if the above code is executed while page first time loading ...
In my case I am loading this grid using ajax (ie,calling a action in cotroller which return a partial view via ajax and replace that resulting html with existing html)... But sorting is not working anymore after relaoding the grid using ajax

Razor WebGrid doesn't keep scrollbar position

Whenever I page or sort my ajax enabled webgrid, my scrollbar position is reset to the top of the page. Is there a way to maintain the scrollbar position?
#model Registrar.WebUI.Models.InstructorPageViewModel
#{
var grid = new WebGrid(canPage: true,
canSort: true,
rowsPerPage: Model.PagingInfo.ItemsPerPage,
ajaxUpdateContainerId: "grid");
grid.Bind(Model.Instructors, rowCount:Model.PagingInfo.TotalItems, autoSortAndPage:false);
grid.Pager(WebGridPagerModes.All);
}
<div id="grid">
#grid.GetHtml(columns: grid.Columns(
grid.Column(format: x => Html.ActionLink("Edit", "Edit", new {id=x.Id})),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name"),
grid.Column("Email"),
grid.Column("UserName", "User Name"),
grid.Column("Phone") )
)
</div>
This is because generated sort link in your header has href="#". I've got the same problem and this is my solution.
This is my _grid.cshtml partial view
#{
var grid = new WebGrid(Model.LeaseOffers, canPage: false, ajaxUpdateContainerId: "offerGrid", ajaxUpdateCallback: "afterLoad()");
}
<div id="offerGrid" class="offer-table-wrapper">
#grid.GetHtml(
rowStyle: "offer-table-tr-odd",
alternatingRowStyle: "offer-table-tr-even",
columns: grid.Columns(
grid.Column("ProviderLogo", "", format: #<img src="#Url.Content(string.Format(Constants.LeaseOfferProviderLogoContentUrlFormat, item.ProviderId))" />, style: "col-first", canSort: false),
grid.Column("ProviderName", "Leasingodawca", format: #<div>#item.ProviderName</div>, style: "col-name"),
grid.Column("DownPayment", "Udział Własny", format: #<div>#item.DownPayment.ToString(Constants.PercentDataToStringFormat)</div>, style: "col-third"),
grid.Column("LeasePeriod", "Okres leasingu", format: #<div>#string.Format(Constants.LeasePeriodDataFormat, item.LeasePeriod)</div>),
grid.Column("LeasePayment", "Rata leasingu", format: #<div>#string.Format(Constants.MoneyDataFormat, item.LeasePayment)</div>),
grid.Column("ResidualValue", "Wartość wykupu", format: #<div>#item.ResidualValue.ToString(Constants.PercentDataToStringFormat)</div>),
grid.Column("TotalLeasePayments", "Suma opłat", format: #<div>#item.TotalLeasePayments.ToString(Constants.PercentDataToStringFormat)</div>),
grid.Column("Actions", "", format: #<div><img src="#Href("~/Modules/LeaseBroker.Orchard.Module/Content/Images/Mockups/wezleasing.png")"/></div>, style: "col-last", canSort: false)
),
htmlAttributes: new { cellpadding = "0", cellspacing = "0" }
)
<script language="javascript">
function afterLoad() {
$("#offerGrid > table > thead > tr > th > a").attr('href', 'javascript:void(0)');
}
jQuery(document).ready(function ($) {
afterLoad();
});
</script>
Just after grid is loading i'm replacing all href attributes in header links into "javascript:void(0)"
You need to make sure that autopostback is disabled, It sounds like your page is redirecting, you just may not be noticing as it is happening so fast.

Resources