Custom message inside the webgrid if empty - asp.net-mvc-3

#if (Model.ActivityCollection.Count > 0)
{
var grid = new WebGrid(source: Model.ActivityCollection, rowsPerPage: 12, canSort: false);
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("EffectiveDate", "Effective Date", style: "date"),
grid.Column("PremiumPaymentAmount", "Premium Payment Amount", style: "amount"),
grid.Column("PaymentType", "Payment Type", style: "date")
));
}
else
{
}
I would like to display a message "No Payment Information Found" inside the web grid in the above else statement. Can someone help me with this?

<div class="grid" style="margin-left:5px;" id="grid">
#if (Model.ActivityCollection.Count > 0)
{
var grid = new WebGrid(source: Model.ActivityCollection, rowsPerPage: 12, canSort: false);
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("EffectiveDate", "Effective Date", style: "date"),
grid.Column("PremiumPaymentAmount", "Premium Payment Amount", style: "amount"),
grid.Column("PaymentType", "Payment Type", style: "date")
));
}
else
{
<div class="grid">
<table cellspacing="0" width="80%">
<thead>
<tr>
<th>Effective Date</th>
<th>Premium Payment Amount</th>
<th>Payment Type</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3" align="center" ><br />No payment information found<br /><br /> </td>
</tr>
</tbody>
</table>
<br/><br/><br/><br/>
</div>
}
</div>

I made this jQuery-function to be triggered when the grid has loaded, and if there is no data in the table it will insert a new row in the empty table to display the text. Much more manageable than building a replica of the WebGrid in HTML.
I added a row style to the Webgrid, to identify the rows (not wanting the header+footer): "webGridDataRow".
function addNoDataTextIfNeeded(){
if($(".webGrid .webGridDataRow").length < 1){ //if there are no data-rows in table, our text should be displayed
var newCell = $("<td>") //create the cell
.attr("colspan", $(".webGrid tr:first th").length) //set colspan so it will span entire grid width (counting the number of column headers)
.text("No data found"); //add the text to be displayed
$("<tr>").append(newCell).appendTo(".webGrid"); //add the cell to a row to the grid :)
}
}

you can do something like this?
public class MyWebGrid : WebGrid
{
public WebGridMkf(IEnumerable<dynamic> source = null,
IEnumerable<string> columnNames = null,
string defaultSort = null,
int rowsPerPage = 10,
bool canPage = true,
bool canSort = true,
string ajaxUpdateContainerId = null,
string ajaxUpdateCallback = null,
string fieldNamePrefix = null,
string pageFieldName = null,
string selectionFieldName = null,
string sortFieldName = null,
string sortDirectionFieldName = null) :
base(source, columnNames, defaultSort, rowsPerPage, canPage, canSort, ajaxUpdateContainerId, ajaxUpdateCallback, fieldNamePrefix, pageFieldName, sortFieldName, sortDirectionFieldName)
{
}
public IHtmlString Table(string tableStyle = null,
string headerStyle = null,
string footerStyle = null,
string rowStyle = null,
string alternatingRowStyle = null,
string selectedRowStyle = null,
string caption = null,
bool displayHeader = true,
bool fillEmptyRows = false,
string emptyRowCellValue = null,
IEnumerable<WebGridColumn> columns = null,
IEnumerable<string> exclusions = null,
Func<dynamic, object> footer = null,
object htmlAttributes = null)
{
if (this.TotalRowCount.Equals(0))
{
return new HtmlString("<div>teste</div>");
}
return base.Table(tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle, selectedRowStyle, caption, displayHeader, fillEmptyRows, emptyRowCellValue, columns, exclusions, footer, htmlAttributes);
}
}
and call:
var grid = new MyWebGrid(
ajaxUpdateContainerId: "grid-test",
rowsPerPage: 10,
defaultSort: "id"
);
grid.Bind(
source: Model.ActivityCollection,
rowCount: Model.ActivityCollection.Count
);
#grid.Table(
alternatingRowStyle: "color1",
rowStyle: "color0",
tableStyle: "webgrid table table-striped table-hover table-condensed",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
footer: #<span></span>,
columns: grid.Columns(
grid.Column(columnName: "id",
header: "ID",
style: "column-id",
canSort: true)
)
)

Related

using ajax loading search data to existing data grid

this is my action method
public ViewResult Index(string firstName)
{
// get the list of employees according to the user name
if (firstName == null)
{
return View((from e in db.Employees
where e.IsActive == true
select e).ToList());
}
else
{
return View((from e in db.Employees
where e.IsActive == true && e.FirstName.Contains(firstName )
select e).ToList());
}
}
This is my view
#{
var grid = new WebGrid(source: Model,
defaultSort: "UserName",
rowsPerPage: 15, ajaxUpdateContainerId: "grid");
}
#using (Html.BeginForm())
{
<div class="btn_align">
#if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Administrator"))
{
<h2>#Html.ActionLink("Create New", "Create")</h2>
}
</div>
<div class="btn_align">
<p>
Find by name:<input class="inputStyle_S" id="firstName" name="firstName" type="text" value="" data-autocomplete= "#Url.Action("QuickSearchFirstName", "ApplyLeave")" />
<input type="submit" id="txtSearch" value="Search" class="btn"/>
</p>
</div>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("User Name", format: (item) => item.FirstName + ' ' + item.LastName),
grid.Column("EmployeeType.Type", "Employee Type"),
grid.Column(header: "Action", format: (item) =>
Html.ActionLink("Details", "Details", new { id = item.id}))
)
)
</div>
}
</div>
<div class="leaveChart_bottom"></div>
I used web grid for representing data
I want get search results to exixting grid without refreshing page , after submiting search button (Search by name)
this is the ajax method I used ,but its not working.Can anyone helpme?
you should use #Ajax.BeginForm it will update your grid without refreshing the page. create a partial class for Grid so that you will get it's RenderHtmlString at server side.
In PartailClass
//GridPartail.cshtml
#model SomeModel
#{
var grid = new WebGrid(source: SomeModel,
defaultSort: "UserName",
rowsPerPage: 15, ajaxUpdateContainerId: "grid");
}
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("User Name", format: (item) => item.FirstName + ' ' + item.LastName),
grid.Column("EmployeeType.Type", "Employee Type"),
grid.Column(header: "Action", format: (item) =>
Html.ActionLink("Details", "Details", new { id = item.id}))
)
)
</div>
now modified your View
#using (#Ajax.BeginForm("Index", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "gridResult" }))
{
<div class="btn_align">
#if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Administrator"))
{
<h2>#Html.ActionLink("Create New", "Create")</h2>
}
</div>
<div class="btn_align">
<p>
Find by name:<input class="inputStyle_S" id="firstName" name="firstName" type="text" value="" data-autocomplete= "#Url.Action("QuickSearchFirstName", "ApplyLeave")" />
<input type="submit" id="txtSearch" value="Search" class="btn"/>
</p>
</div>
<div id="gridResult">
#html.Partail("GridPartail",Model)
</div>
}
NOTE: instead of using Html.BeginForm use Ajax.BeginForm.in your case you have not bind text box to model so that you will get it's value in formCollection
In Controller
[HttpPost]
public ActionResult Index(formCollection coll)
{
string firstName = coll["firstName"];
// get the list of employees according to the user name
if (firstName == null)
{
var result = from e in db.Employees
where e.IsActive == true
select e).ToList();
return PartailView("GridPartail",result );
}
else
{
//"GridPartail.cshtml" is partial viewName
var result = (from e in db.Employees
where e.IsActive == true && e.FirstName.Contains(firstName )
select e).ToList();
return View("GridPartail",result );
}
}
as in AjaxOption i have mention action method POST and you must be pass UpdateTargetId which specify where your result will appear on the view.

MVC3 Webgrid sorting problem with 2nd+ columns

in this sample the sorting of the grid works well with the first column. Every other column can only be sorted ascending, the "sortdir" never switches to "DESC". (Ajax caching is also disabled)
Does anybody knows a solution or had the same problem? What im doing wrong?
Controller:
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult Index_Result_Org(string sort, string sortdir)
{
this.setRep();
this.rep.LoadOV();
return View("Index_OV", rep.GetOV(sort != null ? sort : "Kennung", sortdir != null ? sortdir == "ASC" : true));
}
View:
#model List<Models.OV_View>
#{
Layout = null;
var grid_BA = Html.Grid<OV_View>(Model, ajaxUpdateContainerId: "BAS_OV", canPage: false, defaultSort: "Kennung");
}
<div id="BAS_OV">
#grid_BA.GetHtml(
htmlAttributes: new { #id = "webgrid_BA" },
alternatingRowStyle: "alt",
tableStyle: "BAS",
columns: grid_BA.Columns(
grid_BA.Column("Kennung", header: "Verbandskennung", format: #<text>#Html.Label(#item.Data.Kennung)</text>, canSort: true),
grid_BA.Column("Name", header: "Verbandsname", format: #<text>#item.Data.Name</text>, canSort: true),
grid_BA.Column("Anzahl", header: "Anzahl", format: #<text>#item.Data.Anzahl</text>, canSort: true, style: "counter_column"),
grid_BA.Column("Select", header: "X", canSort: false, format: #<text><input id="Select" name="Select" type="checkbox" onclick="Select(this)" value="#item.Select" #(item.Select == true ? "Checked" : null) /></text>, style: "checkbox_column"),
grid_BA.Column("ID", "", format: #<text>#item.Data.ID</text>, canSort: false, style: "invisible_column")
)
)
</div>
Got it.
Only the defaulSort: Column can be sorted descending.
So i added the following line to the controller:
this.ViewBag.Sort = sort;
And andded and changed the following lines in the view:
var grid_BA = Html.Grid<ErgoBAS_OV_View>(Model, ajaxUpdateContainerId: "BAS_OV", canPage: false, defaultSort: "Kennung");
to:
string temp = this.ViewBag.Sort != null ? this.ViewBag.Sort : "Kennung";
var grid_BA = Html.Grid<ErgoBAS_OV_View>(Model, ajaxUpdateContainerId: "BAS_OV", canPage: false, defaultSort: temp);
This is the dirty solution, think to be clean the defaultSort has to be added to the View Model, thats what i will do now.

If condition or for loop in a webgrid

I am using this webgrid in my view.
<div class="grid">
#{
var grid = new WebGrid(Model.SearchResults, canPage: true, rowsPerPage: 15);
grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(
htmlAttributes: new { #style = "width:100%", cellspacing = "0" },
columns: grid.Columns(
grid.Column(header: "Customer Name", format: (item) => Html.ActionLink((string)item.FullName, "ShowContracts", new { id = item.UserId }, new { #style = "color: 'black'", #onmouseover = "this.style.color='green'", #onmouseout = "this.style.color='black'" })),
grid.Column(header: "SSN", format: item => item.SSN)
))
}
</div>
I search with SSN and display the results in a webgrid. The displayed data is dummy data.
I have a bool AccountVerified in my viewmodel, now I should not give action link to the accounts which are not verified and display text next to them saying account verification pending. Can someone help me on this?
Try the following:
grid.Column(
header: "Customer Name",
format: (item) =>
(bool)item.AccountVerified
? Html.ActionLink(
(string)item.FullName,
"ShowContracts",
new {
id = item.UserId
},
new {
style = "color: 'black'",
onmouseover = "this.style.color='green'",
onmouseout = "this.style.color='black'"
}
)
: Html.Raw("pending")
)
or write a custom HTML helper to avoid this monstrosity and simply:
grid.Column(
header: "Customer Name",
format: item => Html.PendingLink(item)
)

How to Navigate to a view spacifying the view name and controller when i click a row in mvc3 webgrid?

<div style="text-align:center" class="grid">
#{
var grid = new WebGrid(Model.SearchResults, canPage: true, rowsPerPage: 15);
grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(headerStyle: "webgrid-header", footerStyle: "webgrid-footer", selectedRowStyle: "webgrid-selected-row", alternatingRowStyle: "webgrid-alternating-row", rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column(header: "Customer Name", style: "text-align-center", format: (item) => Html.ActionLink((string)item.FullName, "ShowContracts", new { id = item.UserId }, new { #style = "color: 'black'", #onmouseover = "this.style.color='green'", #onmouseout = "this.style.color='black'" })),
grid.Column(header: "SSN", style: "text-align-center", format: item => item.SSN)
))
}
</div>
For now I am clicking an item in a row and navigatin to a different page, but i want to click on a row to navigate.
Thanks for any help.

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