I've been searching for examples but can't seem to find how I can use Bootstrap inside of a grid column in order to create a button. The following works but I would like to display an Edit button instead of just the text.
#grid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
rowStyle: "webgrid-row-style",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
footerStyle: "webgrid-footer",
columns: grid.Columns(
grid.Column(columnName: "CustomerName", header: "Customer Name"),
grid.Column(columnName: "Subject", header: "Subject"),
grid.Column(columnName: "CallDate", header: "Call Date"),
grid.Column(columnName: "Status", header: "Status"),
grid.Column(header: "Edit", format: (item) =>
{
var link = Html.ActionLink("Edit", "Edit", new { id = item.Id });
return link;
}),
Anyone know of an example I an look at to convert the Edit column to using a Bootstrap button?
Try adding the style argument for that specific column like so:
grid.Column(header: "Edit", format: (item) =>
{
var link = Html.ActionLink("Edit", "Edit", new { id = item.Id });
return link;
}, style: "btn btn-default")
I want to add checkbox in my webgrid so anybody can tell me how can I do this? And also tell me how can I select all checkbox and delete them. This is my code:-
#{
var grid = new WebGrid(
Model, rowsPerPage: 5,
defaultSort: "CatagoryId",
columnNames: new[] { "Category_Name", "Parent_Category_ID", "Category_Desc", "IsGenderApplicable", "IsAgeApplicable", "IsActive" }
);
}
#grid.GetHtml(
fillEmptyRows: false,
mode: WebGridPagerModes.All,
columns:grid.Columns(
grid.Column("Category_Name", header: "Catagory Name"),
grid.Column("Parent_Category_ID", header: "Parant CatID"),
grid.Column("Category_Desc", header: "Description"),
grid.Column("IsGenderApplicable", header: "Gender Application"),
grid.Column("IsAgeApplicable", header:"Age Application"),
grid.Column("IsActive", header: "Active")
)
)
Add a checkbox as:
grid.Column(format: #<text><input name="chkbox"
type="checkbox" value="some value" /></text>),
Your second query: how can I select all checkbox ?
Please refer to this blog: http://www.codeproject.com/Questions/273164/mvc-checkbox-checked-rows-in-the-web-grid
I had read some tutorials of how to implement a MVC webgrid through AJAX but I want to understand what's happening under the hood, and which is the correct implementation for ajaxUpdateContainerId.
Example A:
#{
var grid = new WebGrid(Model, rowsPerPage: 10, ajaxUpdateContainerId: "result");
#grid.GetHtml(htmlAttributes: new { id = "result" }, tableStyle: "webgrid",
grid.Columns(
grid.Column(columnName: "ID", header: "ID", canSort: true),
grid.Column(columnName: "Name", header: "Name", canSort: true)))
}
Example B
#{
var grid = new WebGrid(Model, rowsPerPage: 10, ajaxUpdateContainerId: "result");
<div id="result">
#grid.GetHtml( tableStyle: "webgrid",
grid.Columns(
grid.Column(columnName: "ID", header: "ID", canSort: true),
grid.Column(columnName: "Name", header: "Name", canSort: true)))
</div>
}
Example C:
<div id="result">
#{
var grid = new WebGrid(Model, rowsPerPage: 10, ajaxUpdateContainerId: "result");
#grid.GetHtml(tableStyle: "webgrid",
grid.Columns(
grid.Column(columnName: "ID", header: "ID", canSort: true),
grid.Column(columnName: "Name", header: "Name", canSort: true)))
}
</div>
I know that you have to bind the content to the grid and that you have to pass only the elements that you are going to display in the webgrid, but I'm trying to understand how ajaxUpdateContainerId works, so this examples work for this purpose.
Which of this examples is the correct way to update the content and why?
ajaxUpdateContainerId is doing a "Update" or really is doing a Replace content?
I hope someone can help me with this and this can be useful to someone else. Thanks In advance.
After a lot of tests I get the answer for this:
Which of this examples is the correct way to update the content and why?
The three examples are correct and will work, which one to use will depend on your needs, in my specific case I will use the Example A because I only want to update the content of the table(WebGrid) not everything inside the div, if for some reason every time you sort or change page you want to update something else you should use Example C.
Example B is pretty much like Example A but I don't need to put an extra div.
ajaxUpdateContainerId is doing a "Update" or really is doing a Replace content?
It's doing a update and will only update the content of the element with the specified ID in this case result.
And to understand how this works in Example A I did this:
#Html.Label("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
#{
var grid = new WebGrid(Model, rowsPerPage: 10, ajaxUpdateContainerId: "result");
#grid.GetHtml(htmlAttributes: new { id = "result" }, tableStyle: "webgrid",
grid.Columns(
grid.Column(columnName: "ID", header: "ID", canSort: true),
grid.Column(columnName: "Name", header: "Name", canSort: true)))
}
If you page/sort in the webgrid the time label will not change and this is
the expected behavior only the content of the table will change, if you do the same in the Example C and everything is wrapped inside the div every time you page/sort you will see that all the content will be updated including the time label.
This seems pretty logic now but I was confused how this works so I hope this can be useful to some one else.
Note: I was having a weird behavior where after paging and sorting I get an empty page with the content of the grid and it turns that it was because I was using history.js and I was pushing the content of the div that was wraping my partial view(which it's ok for Example C) but I was using Example A and really what I want is to push only the content of my webgrid wich is the one that was changing.
I have a webgrid defined within a partial view. (This is an MVC 4 project.) The webgrid isn't the only thing in the partial view, so the webgrid is bound to a List within the model of the partial view.
The grid populates and sorts as it should when a column header is clicked, but when I repopulate the grid by a call to an action method (via a form post set up using Ajax.BeginForm) and then click on a column header, the grid contents disappear. (The action method queries a database using search criteria provided on the form by the user.)
What could be causing this? How can it be resolved?
The partial view starts with:
#model DonationImport.Models.GiftWithSplits
The contents of the partial view are within a form designated by:
#using (Ajax.BeginForm("SearchConstit", "Batch", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "constitSearchArea" }))
The WebGrid is defined as follows:
#{
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>
}
When one clicks on:
<input type="submit" value="Search" />
within the form, the action method called is as follows:
[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);
}
As you can probably tell, I am a beginner in this MVC approach.
Additional thoughts (added later)...
It seems the source of the problem is that the links generated by the WebGrid HTML help for the column headers are based on the URL related to the action method which produced the grid. When the grid is first displayed, the link is: /Batch/Verify/34?sort=FirstName&sortdir=ASC since the grid was build as a part of the entire Verify view (coming out of the Verify action method). But, when one searches for manually-entered search criteria, the grid is build from the SearchConstit action method which populates only a partial view, so the URL in the column header link is now: /Batch/SearchConstit?sort=FirstName&sortdir=ASC.
Also, the "Search" button is associated with a POST because it needs to pass data from the form fields to use as search criteria; whereas, the WebGrid column headers are using a GET, and apparently there is no way to force them to POST. So, the problem seems to boil down to how to pass the search criteria from the form fields without posting the form.
I can think of a possible solution using Session variables, but I'm hesitant to do it that way.
Another option might be to abandon the use of the WebGrid.
Any ideas?
I found your question, when i was searching solution for same problem. I also faced same problem. I have used web grid to display data.
I have used filter/pagination. I used text box for search in grid also.
I am making post call for search. Webgrid was disappearing when i clicked filter and paging button. I google a lot and didn't find any solution. Finally i found solution so thought of posting.
You need to use get ajax call instead of post call that will solve you problem. Do not use beginform post for search.
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
The Solution is pretty simple, you need to do a GET, whenever you sort or page the web gird, it will try to get data and hit the a HttpGet Action, this will work as follows:
[HttpGet]
public ActionResult YourActionMethod()
{
return PartialView("YourView",YourModel);
}
The best part is, upon sorting, the request will send a parameter named as "sortBy" too, you can use this here and decide what you want to do with the binded Model with the grid. You can inspect what URL the Sort header will hit by using the "Developer Tools" in your browser.
Note : By default the action method it would be hitting would be same as the controller name.
I have a webgrid
#{
var gdAdminGroup = new WebGrid(source: Model, rowsPerPage: 20, ajaxUpdateContainerId: "tdUserAdminGroup");
}
#gdAdminGroup.GetHtml(
htmlAttributes: new { id = "tdUserAdminGroup" },
tableStyle: "gd",
headerStyle: "gdhead",
rowStyle: "gdrow",
alternatingRowStyle: "gdalt",
columns: gdAdminGroup.Columns(
gdAdminGroup.Column(columnName: "Description", header: "Admin Group"),
gdAdminGroup.Column(header: "", format: #<text><input name="chkUserAdminGroup" type="checkbox" value="#item.AdminGroupID" #(item.HasAdminGroup == 0? null : "checked") /></text>)
)
)
If I check some checkboxs and goes to the second page, the selection on the first page will be lost. Can anyone help me with this? Thank you
The Page selection is links why
- The page is refeshed via a GET command (< a href="...." not < input type="submit" ....)
- The link does not submit form in which you checkbox is in, why you can not read the state of the checkbox.
Either you should look for a JavaScript solution to amend the Checkbox data in the GET URL,
or find another Grid generator.
http://mvccontrib.codeplex.com/wikipage?title=Grid&ProjectName=mvccontrib