How to display an image in webgrid - asp.net-mvc

I need to display an image in the column of a webgrid. Webgrid is filled using the list returned from the controller.I used the below code in view and controller respectively:
#using (Html.BeginForm(null, null, FormMethod.Post ))
{
<div id ="DivGrid">
#{
WebGrid grid = new WebGrid(source: Model);
#grid.GetHtml(htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
grid.Column(format: #<img src="#Href("vPath")"/>),
grid.Column("title","Product Name"),
grid.Column("user_ID","User ID"),
grid.Column("", format: #<text>#Html.ActionLink("Edit", "EditOrder", "OrderStatus", new { id = item.ID})</text>)));
// grid.Column("", format: #<text>#Html.ActionLink("Delete", "DeleteOrder", "OrderStatus", new { id = item.ID}, new { onclick = "return confirm('Are you sure you wish to delete this Order status?');" })</text>)));
}
</div>
using (APM context = new APM())
{
lstorder = (from s in context.T_Order
join p in context.T_OrderDetails on s.ID equals p.Order_ID
join t in context.T_OrderDetailSpecification on p.ID equals t.OrderDetails_ID
join r in context.M_Product on p.Product_ID equals r.ID
where s.OrderStatus_ID == 1 && p.IsPreviewRequired == 1 && p.OrderStatus_ID == 1
select new orderList
{
ID = p.ID,
vPath = r.VirtualPath,
product_ID = r.ID,
title = r.Title,
amount = t.Value,
user_ID= (int)s.User_ID,
sel_ID= (int)p.SelectionList_ID
}).ToList();
return View(lstorder);
}
But the code 'grid.Column(format: #<img src="#Href("vPath")"/>),' not displaying the image .it simply showing the path something like /views/PreviewRequest/vPath

Try this :
I changed
grid.Column(format: #<img src="#Href("vPath")"/>)
to
grid.Column(format: #<img src="#Href(item.vPath)"/>),

Related

Kendo Grid filter not working with foreign key column Model

My Grid Columns:
#(Html.Kendo().Grid<Kendo_UI_Bootstrap_Integration.Models.DTO.GridDto>()
.Name("GridName")
.Filterable(f => f.Mode(GridFilterMode.Menu).Extra(false))
.EnableCustomBinding(true)
.Columns(
columns =>
{
columns.ForeignKey(c => c.HouseId, Model.Homes, "HouseGuid", "HouseName")
.EditorTemplateName("HouseDropDown")
.Title("House Name")
.Filterable(f => f.UI("$.proxy(GridFilter, {field: 'Id'})").Operators(o => o.ForString(e => e.Clear().IsEqualTo("Is equal to").IsNotEqualTo("Is not equal to"))));
columns.ForeignKey(c => c.NameId, Model.Names, "NameGuid", "Name")
.EditorTemplateName("NameDropDown")
.Title("Name")
.Filterable(f => f.UI("$.proxy(GridFilter, {field: NameId})").Operators(o => o.ForString(e => e.Clear().IsEqualTo("Is equal to").IsNotEqualTo("Is not equal to"))));
Grid Filter:
function GridFilter(element) {
var grid = "GridName";
var fieldName = this.field;
var gridDataItems = $("#" + grid).data("kendoGrid").dataSource.data();
var listDataItems = [];
for (var i = 0; i < gridDataItems.length; i++) {
if (gridDataItems[i][fieldName] !== null && $.inArray(gridDataItems[i][fieldName], listDataItems) < 0) {
listDataItems.push(gridDataItems[i][fieldName]);
}
}
listDataItems.sort();
$(element).prop("id", fieldName + "DropDown");
element.kendoDropDownList({
dataSource: {
data: listDataItems
}
})
}
I pass in my ViewModel at the top of the view, the Model consists of a list of Homes and a list of Names from the database.
I want to filter the grid based from the contents of the grid, but the filter function I have specified dosnt get hit and the contents of the model is instead used to populate the filter.
How can I have the filter just look at the contents of the grid instead?

Adding a default value to selected list Razor

I am populating a dropdown like this
primaryDrop = new Dictionary<string, string>()
{
{"1", "Getting ready"},
{"2", "Starting"},
{"3", "All"},
{"4", "Other"}
};
PrimaryDrop = primaryDrop.Select(item => new SelectListItem
{
Value = item.Key,
Text = item.Value
});
And displaying it like this
#Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text"), "Select ...", new { #class = "form-control" })
How can I select a default value to 'Other' for example
Was thinking something like this
#Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text", new { SelectedItem = "Other" }), "Select ...", new { #class = "form-control" })
but doesn't work
You don't need to create an object to specify the selected item, you just need to give the value you want. In your case, Other has a value of 4:
#Html.DropDownListFor(m => m.SelectedPrimary,
new SelectList(ViewBag.PrimaryDrop, "Value", "Text", "4"),
"Select ...",
new { #class = "form-control" })
You can achieve it by server code, when you populate data
PrimaryDrop = primaryDrop.Select(item => new SelectListItem
{
Value = item.Key,
Text = item.Value,
Selected = item.Key == "4" // Or item.Value== "Others"
});
Or we can set value for SelectedPrimary of model
SelectedPrimary = "4"

Default Empty Option for MVC dropdown menu

I have the following DropDownListFor that displays a list of states for the user to choose from. How can I default the dropdown to be empty. It currently defaults to the first state in alphabetical order ("Alaska")
#Html.DropDownListFor(m => m.User.StateID,
new SelectList(Model.User.States.Where(filter => filter.Active && (filter.CountryID == 1))
.Select(item => new
{
ID = item.StateProvinceID,
Description = item.Name
}),
"ID",
"Description",
Model.User.StateID),
new { #data_bind = "value: user.StateID, enable:!isSiteUser()", tabindex = "10" })
I figured out that one of the posted questions did have the correct answer for my problem. I was just trying to do use it incorrectly. I was adding "string.Empty" to the wrong location. This is the solution.
#Html.DropDownListFor(m => m.User.StateID,
new SelectList(Model.User.States.Where(filter => filter.Active && (filter.CountryID == 1))
.Select(item => new
{
ID = item.StateProvinceID,
Description = item.Name
}),
"ID",
"Description",
Model.User.StateID),
string.Empty,
new { #data_bind = "value: user.StateID, enable:!isSiteUser()", tabindex = "10" })

How to format date in mvc web grid

I have a web grid and I am not using razor syntex.Rather I am using the .aspx form.
the code is below;
<%
var grid = new WebGrid(Model,defaultSort:"PublishDate",rowsPerPage:10);
%>
<%:
grid.GetHtml(
tableStyle: "wGrid",
headerStyle: "wGridHeader",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Title", canSort: false),
grid.Column("PublishDate", "Published on"),
grid.Column("CategoryName", "Category"),
grid.Column(format: (item) => Html.ActionLink("Details", "Browse", new { id = item.Title }))
)
)
%>
Now I want to format the 'PublishDate' column to something like 'dd-MMM-yyyy'.
Any idea how to do this?
grid.Column(
"PublishDate",
"Published on",
format: (item) => string.Format("{0:dd-MMM-yyyy}", item.PublishDate)
)
If DateTime Property is defined as (can contain null) :
public DateTime? WorkedDate { get; set; }
Use this format:
grid.Column("WorkedDate", "Last Worked On",
format: (item) => item.WorkedDate != null
? item.WorkedDate.ToString("MM/dd/yy") : "", canSort: true)
Otherwise if it is defined as below (can't be null), it will have either actual date or .MinDate as the default.
public DateTime WorkedDate { get; set; }
Use format:
grid.Column("WorkedDate", "Last Worked On",
format: (item) => item.WorkedDate != DateTime.MinValue ?
item.WorkedDate.ToString("MM/dd/yy") : "", canSort: true)
This works for me, and allows for Null values
grid.Column("End_Date",format: item => ((item.End_Date == null) ? "" : item.End_Date.ToString("MM/dd/yyyy"))),
This worked for me:
grid.Column("Date_Of_Birth", "Date Of Birth", format: item => ((item.Date_Of_Birth == null) ? "" : item.Date_Of_Birth.ToString("MM/dd/yyyy")))

Create serial number column in telerik mvc grid

I could create a grid with telerik mvc
<% Html.Telerik().Grid(Model)
.Name("ProductGrid")
.Columns(columns => {
columns.Bound(h => h.ProductName).Width("34%");
columns.Bound(h => h.Description).Width("60%");
columns.Bound(h => h.ProductID).Format(Html.ImageLink("Edit", "Products", new { Id = "{0}" }, "/Content/images/icon_edit.gif", "", new { Id = "edit{0}" }, null).ToString()).Encoded(false).Title("").Sortable(false).Width("3%");
columns.Bound(h => h.ProductID).Format(Html.ImageLink("Delete", "Products", new { Id = "{0}" }, "/Content/images/icon_delete.gif", "", new { onclick = string.Format("return confirm('Are you sure to delete this add on?');") },null).ToString()).Encoded(false).Title("").Sortable(false).Width("3%");
})
.EnableCustomBinding(true)
.DataBinding(databinding => databinding.Ajax().Select("_Index", "ProductGrid"))
.Pageable(settings => settings.Total((int)ViewData["TotalPages"])
.PageSize(10))
.Sortable()
.Render(); %>
but I need to add a serial number column in telerik grid.How can i do this?
I think the best way is to use template column like this.
<%
var sn = 0;
Html.Telerik().Grid(Model).Name("Grid").HtmlAttributes(new { style = "width:auto" })
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Template(c=> {%> <%: ++sn %> <% }).Title("S/N");
columns.Bound(c => c.CustomerNumber);
columns.Bound(c => c.Narration);
})
.Render(); %>
This way you don't have to be adding serial number property to your view models.
Hope this help?
I think the best way to do this is to add a SerialNumber column to your Product class which is your model and than just add another bound column to the grid like this:
columns.Bound(h => h.SerialNumber)
If you pass a List of Products you can populate the SerialNumber column like this:
List<Product> products = GetList(); // Your method to get data here
int counter = 1;
products.ForEach(x => x.SerialNumber = counter++);
If you want to support consistent numbers with paging you have to calculate yourself the initial value of the counter valuable. For this purpose you must have the current page and page size.
In MVC Web Grid
use this calculation
grid.Column(header: "#",
format: item => item.WebGrid.Rows.IndexOf(item) + 1 + Math.Round(Convert.ToDouble(grid.TotalRowCount / grid.PageCount) / grid.RowsPerPage) * grid.RowsPerPage * grid.PageIndex),

Resources