Kendo Grid AJAX Bound Not Updating MVC4 - asp.net

I am trying to get my grid to update for the opt-in status, but when I hit update no action occurs. I an using ajax binding with a model and entity framework. When I hit cancel it will follow this method. I am not sure what I am missing as everything else functions and compiles.
View
<div class="row">
<h2>PQA Opt-In</h2>
<br />
#(Html.Kendo().Grid<TelerikMvcApp1.Models.PQAViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(opt => opt.Jobber).Width(90);
columns.Bound(opt => opt.Dealer).Width(95);
columns.Bound(opt => opt.OptInd).Width(110);
columns.Bound(opt => opt.establish_date_time);
columns.Bound(opt => opt.establish_id);
columns.Command(commands =>
{
commands.Edit();
}).Title("Commands").Width(200);
})
.DataSource(datasource => datasource
.Ajax()
.Model(model =>
{
model.Id(opt => opt.Jobber);
model.Field(opt => opt.Jobber).Editable(false);
model.Field(opt => opt.Dealer).Editable(false);
model.Field(opt => opt.establish_date_time).Editable(false);
model.Field(opt => opt.establish_id).Editable(false);
})
.PageSize(20)
.Read(read => read.Action("ProductQualityFileFull_Read", "PQA"))
.Update(update => update.Action("Opt_Update", "PQA"))
)
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Filterable()
.Pageable()
)
</div>
Controller
sing System;
using System.Linq;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using TelerikMvcApp1.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace TelerikMvcApp1.Controllers
{
public class PQAController : Controller
{
public ActionResult Baseline()
{
return View();
}
public ActionResult ProductQualityFileFull_Read([DataSourceRequest] DataSourceRequest
request)
{
using (var pqa = new PQAEntities())
{
IQueryable<ProductQualityFileFull> opt = pqa.ProductQualityFileFulls;
DataSourceResult result = opt.ToDataSourceResult(request, ProductQualityFileFull =>
new PQAViewModel
{
Jobber = ProductQualityFileFull.Jobber,
Dealer = ProductQualityFileFull.Dealer,
OptInd = ProductQualityFileFull.OptInd,
establish_date_time = ProductQualityFileFull.establish_date_time,
establish_id = ProductQualityFileFull.establish_id
});
return Json(result);
}
}
public ActionResult UpdateOptIn()
{
return View();
}
public ActionResult Opt_Update([DataSourceRequest] DataSourceRequest request,
PQAViewModel opt)
{
if (ModelState.IsValid)
{
using (var pqa = new PQAEntities())
{
var entity = new ProductQualityFileFull
{
Jobber = opt.Jobber,
Dealer = opt.Dealer,
OptInd = opt.OptInd,
establish_date_time = opt.establish_date_time,
establish_id = opt.establish_id
};
pqa.ProductQualityFileFulls.Attach(entity);
pqa.Entry(entity).State = EntityState.Modified;
pqa.SaveChanges();
}
}
return Json(new[] { opt }.ToDataSourceResult(request, ModelState));
}
}
}
Model
namespace TelerikMvcApp1.Models
{
public class PQAViewModel
{
public string Jobber { get; set; }
public int Dealer { get; set; }
public int OptInd { get; set; }
public DateTime establish_date_time { get; set; }
public string establish_id { get; set; }
}
}

You have made all your columns non-editable - which means you will not make any changed to the model. And if no change is made - no update request is performed. Make a change to your model and the update should be triggered.

Related

Kendo ui grid fails at canceling the inline edit on aspnet mvc

I have come across a frustrating issue lately. I'm using kendi ui Grid on asp.net mvc ... the problem I'm running into is when I switch grid editable mode on and add the edit command and model Id, everything seems to be working but there are issues. First it doesn't hit the edit action on the controller then if I cancel the edit, the row is going to disappear!
This is my model
public class ContactInformation
{
[Key]
[ScaffoldColumn(false)]
public long ContactInfoId { get; set; }
public string Position { get; set; }
[Required]
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string CodeToPerson { get; set; }
public string Fax { get; set; }
public string CellPhoneNumber { get; set; }
public string Email { get; set; }
public virtual Client Client { get; set; }
}
This is the controller
public class ContactsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: dashboard/Contacts
public ActionResult Default(string id)
{
if(id != null)
{
ViewBag.clientGuid = id;
var model = db.Clients.SingleOrDefault(x=>x.ClientGuid == id);
model.BillingAddresses = db.BillingAddresses.Where(x => x.Client.ClientId == model.ClientId).ToList();
return View(model);
}
return View();
}
public ActionResult Contacts_Read([DataSourceRequest]DataSourceRequest request, string id)
{
var contacts = (id != null) ?
db.ContactInfos.Where(x => x.Client.ClientGuid == id).ToList() :
db.ContactInfos.ToList();
return Json(GetContacts(contacts).ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Contacts_Create([DataSourceRequest]DataSourceRequest request,ContactInformation model)
{
// Todo: save the model
return Json(ModelState.ToDataSourceResult());
}
[HttpPost]
public ActionResult Contacts_Update([DataSourceRequest]DataSourceRequest request, ContactInformation model)
{
if(model != null)
{
var contactToUpdate = db.ContactInfos.Find(model.ContactInfoId);
contactToUpdate.Name = model.Name;
contactToUpdate.Position = model.Position;
contactToUpdate.PhoneNumber = model.PhoneNumber;
contactToUpdate.CodeToPerson = model.CodeToPerson;
contactToUpdate.CellPhoneNumber = model.CellPhoneNumber;
contactToUpdate.Fax = model.Fax;
contactToUpdate.Email = model.Email;
contactToUpdate.Client = db.Clients.Find(model.Client.ClientId);
db.SaveChanges();
}
return Json(ModelState.ToDataSourceResult());
}
public IEnumerable<ContactInformation> GetContacts(List<ContactInformation> contacts)
{
return contacts.Select(contactInfo => new ContactInformation
{
Position = contactInfo.Position,
Name = contactInfo.Name,
PhoneNumber = contactInfo.PhoneNumber,
CodeToPerson = contactInfo.CodeToPerson,
Fax = contactInfo.Fax,
CellPhoneNumber = contactInfo.CellPhoneNumber,
Email = contactInfo.Email,
Client = new Client()
{
CompanyName = contactInfo.Client.CompanyName,
IndustryCategory = contactInfo.Client.IndustryCategory,
IndustrySubCategory = contactInfo.Client.IndustrySubCategory
}
});
}
}
This is the view
#(Html.Kendo().Grid<ContactInformation>().Name("Contacts")
.Columns(
columns.Bound(c => c.Client.IndustryCategory).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Client.IndustrySubCategory).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Name).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Position).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.PhoneNumber).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.CodeToPerson).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.CellPhoneNumber).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Fax).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Email).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Command(command =>
{
command.Edit();
}).Width(100);
})
.ToolBar(tools =>
{
tools.Excel();
})
.Excel(excel => excel
.FileName("ContactsData.xlsx")
.Filterable(true)
.ProxyURL(Url.Action("Excel_Export_Save"))
)
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Scrollable()
.Sortable()
.Groupable()
.Events(events=>events.Cancel("error_handler"))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.HtmlAttributes(new { style = "height:500px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Model(Model=> {
Model.Id(c => c.ContactInfoId);
Model.Field(c => c.Client.IndustryCategory).Editable(false);
Model.Field(c => c.Client.IndustrySubCategory).Editable(false);
})
//.Create(create => create.Action("Contacts_Create", "Contacts"))
.Read(read => read.Action("Contacts_Read", "Contacts", new { id = ViewBag.clientGuid }))
.Update(update => update.Action("Contacts_Update", "Contacts", new { id = ViewBag.clientGuid }))
.PageSize(20)
)
.ColumnMenu()
)
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function() {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
The interesting thing, there is another model called inquiry in the project that has grid the same as this one and it works quite fine. Actually, they are quite identical but I couldn't figure it out why this doesn't work like the other!
First thing I see here is that your method in controller is HttpPost but in the definition of update function (on Telerik grid) you didn't specify it. It means, that grid is trying to trigger default one - and it is HttpGet -> that's why update is not triggered.
You need to define that update method is Post
.Update(update => update.Action("Contacts_Update", "Contacts", new { id = ViewBag.clientGuid }).Type(HttpVerbs.Post))

What is causing my ToDataSourceResult error in my KendoUI Core Application?

I have created a .NET Core application with WebAPI and KendoUI. I've added a generic repository, when I try to add a datasource to my Kendo Grid I am getting an error on the .ToDataSourceResult() message of:
< Task< IEnumerable< Vessel>> does not contain a definition for
'ToDataSourceResult' and the best extension method overload
'QueryableExtensions.ToDataSourceResult(DataTable, DataSourceRequest)'
requires a receiver of type 'DataTable'
I followed the Kendo documentation for Core and WebApi to complete this method but I can't get it to work. I've attached the code from my project related to this error and data.
Controllers/HomeController
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc;
using Senua.Interfaces;
using Senua.Models;
using System.Diagnostics;
namespace Senua.Controllers
{
public class HomeController : Controller
{
private IVesselRepository service;
public IActionResult Index()
{
return View();
}
[HttpGet]
public DataSourceResult GetVessels([DataSourceRequest]DataSourceRequest request)
{
return service.GetAllVesselsAsync().ToDataSourceResult(request); <----Error appears here.
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Views/Home/Index
#(Html.Kendo().Grid<Senua.Models.Vessel>()
.Name("vessel_grid")
.Columns(columns =>
{
columns.Bound(p => p.Name);
})
.Pageable()
.Filterable()
.DataSource(dataSource =>
dataSource
.WebApi()
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.Id);
})
.Read(read => read.Action("GetVessels", "Home"))
))
<script>
function error_handler(e) {
var errors = $.parseJSON(e.xhr.responseText);
if (errors) {
alert("Errors:\n" + errors.join("\n"));
}
}
</script>
DAL/VesselRepository
using Senua.Interfaces;
using Senua.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Senua.DAL
{
public class VesselRepository : Repository<Vessel>, IVesselRepository
{
public VesselRepository(LocalContext repositoryContext)
: base(repositoryContext)
{
}
public async Task<IEnumerable<Vessel>> GetAllVesselsAsync()
{
var vessel = await FindAllAsync();
return vessel.OrderBy(x => x.Name);
}
}
Interfaces/IVesselRepository
using Senua.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Senua.Interfaces
{
public interface IVesselRepository
{
Task<IEnumerable<Vessel>> GetAllVesselsAsync();
Task<Vessel> GetVesselByIdAsync(int Id);
Task CreateVesselAsync(Vessel vessel);
Task UpdateVesselAsync(Vessel vessel);
Task DeleteVesselAsync(Vessel vessel);
}
}
DAL/Repository
using Senua.Interfaces;
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Senua.DAL
{
public abstract class Repository<T> : IRepository<T> where T : class
{
protected LocalContext DbContext { get; set; }
public Repository(LocalContext _context)
{
this.DbContext = _context;
}
public async Task<IEnumerable<T>> FindAllAsync()
{
return await this.DbContext.Set<T>().ToListAsync();
}
}
}
Interfaces/IRepository
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Senua.Interfaces
{
public interface IRepository<T>
{
Task<IEnumerable<T>> FindAllAsync();
Task<IEnumerable<T>> FindByConditionAsync(Expression<Func<T, bool>> expression);
void Create(T entity);
void Update(T entity);
void Delete(T entity);
Task SaveAsync();
}
}
I need some guidance on this one, I've never set up an async repos before so it's a little new however, from what I can see, it's ok and I've tested with postman. I noticed that there is also a 'ToDataSourceAsync' but, after trying that as well it didn't work either.
TIA
For ToDataSourceResult, it is the method for IEnumerable.
For GetAllVesselsAsync(), it returns a task.
Try code below
[HttpGet]
public async Task<DataSourceResult> GetVessels([DataSourceRequest]DataSourceRequest request)
{
var result = await service.GetAllVesselsAsync();
return result.ToDataSourceResult(request);
}
Update
public class HomeController : Controller
{
private IVesselRepository service;
public HomeController(IVesselRepository service)
{
this.service = service;
}
Here's my Kendo MVC Grid that needed async functionality.
It's a complex case where you need to use an asynchronous DataSourceResult to bind grid data from an api:
public class HomeController : Controller
{
private HttpClient _client = ApiHelper.Client;
private Uri baseUri = ApiHelper._Client.BaseAddress;
public ActionResult Index()
{
return View();
}
DataSourceResult result;
JsonResult final;
public async Task<ActionResult> GetList([DataSourceRequest] DataSourceRequest request)
{
int offset = 0;
const int limit = 100;
List<myModel> myModelList = new List<myModel>();
using (var req = new HttpRequestMessage(HttpMethod.Get, baseUri + ConfigurationManager.AppSettings["V3BaseUri"] + "resource?offset=" + offset + "&limit=" + limit))
using (var response = await ApiHelper.Client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
try
{
var content = response.Content.ReadAsStringAsync().Result;
myModelList = JsonConvert.DeserializeObject<List<myModel>>(content);
result = await myModelList.ToDataSourceResultAsync(request);
final = Json(result);
return final;
}
catch (Exception exc)
{
string message = exc.Message;
Console.WriteLine("Exception message: {0}", message);
throw;
}
}
}
And in my view:
#(Html.Kendo().Grid<Project.Models.myModel>()
.Name("grid")
.AutoBind(true)
.Columns(columns =>
{
columns.Bound(c => c.Id)
.Width(80).Title("Entity Id");
columns.Bound(c => c.NameOfInstitution);
columns.Bound(c => c.Addresses).ClientTemplate("#=generateAddress(Addresses)#").Title("Address");
columns.Bound(c => c.InstitutionTelephones).ClientTemplate("#=generatePhone(InstitutionTelephones)#").Title("Phone");
})
.HtmlAttributes(new { style = "height: 750px;" })
.Scrollable()
.Groupable()
.Sortable()
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(99)
.Read(read => read.Action("GetList", "Home"))
).NoRecords(x => x.Template("<div class='empty-grid'>NO RECORDS</div>")))

Ajax Binding a Kendo Grid with Asp.Net MVC doesn't display anything

I am trying to bind a Kendo Grid with Asp.Net MVC. I show that grid in a detail page View with a lot of other fields...
The records are coming correctly but nothing is displayed in the grid.
Here is the Grid code, in the user control (ascx), of the View:
<% Html.Kendo().Grid<Web.Areas.WorkOrder.ViewModels.PartListViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.GlassType);
columns.Bound(p => p.WorkType);
columns.Bound(p => p.PartNumber);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetPartListInfo", "Claim", new { id = Model.JobId }))
.PageSize(5)
.ServerOperation(false)
)
.Pageable()
.Sortable()
.Groupable()
.Filterable()
.Render();
%>
The Model View looks like this:
public IEnumerable<PartListViewModel> PartList { get; set; }
public string VIN { get; set; }
public string Invoice { get; set; }
public string MileageKM { get; set; }
public EntityModel Provider { get; set; }
public string Comments { get; set; }
…etc, etc
This is the code from my Controller:
public ActionResult GetPartListInfo([DataSourceRequest] DataSourceRequest request, string id)
{
XrmServiceContext xrmServiceContext = new XrmServiceContext();
workorder workOrder = xrmServiceContext.workorderSet.Where(i => i.Id == new Guid(id)).FirstOrDefault();
IEnumerable<PartListViewModel> parts = (xrmServiceContext.workorderproductSet.Where(prod => prod.WorkOrder.Id == workOrder.Id))
.Select(x => new PartListViewModel
{
WOId = id,
Id = x.f1_Product.Id.ToString(),
Quantity = 3,
PartNumber = "WS",,
WorkType = "Repair",
GlassType = "Windshield",
Price = 133
}).ToList();
return Json(parts.ToDataSourceResult(request));
}
Am I missing something in my configuration? I am wondering what is going wrong with it?
Thanks for any help you can provide.
try adding this to allow a get:
return Json(parts.ToDataSourceResult(request),JsonRequestBehavior.AllowGet);

ASP.NET MVC 3 Telerik Razor grid with editable foreign key dropdown column

I am trying to create an Ajax Telerik grid in Razor that has an updateable foreign key column that shows a dropdown list. I've copied my page pretty much like the example, and everything works. I can add new records, delete them and edit them. The only thing that doesn't work is that I get a textfield with the integer when I update a record in my grid, instead of a dropdown list with all the possibilities of the foreign key table.
Anyone have any ideas on how I could fix this? See code below.
Telerik grid:
#(Html.Telerik().Grid<EditableAccount>()
.Name("Grid")
.ToolBar(commands => commands.Insert().ButtonType(GridButtonType.Text).ImageHtmlAttributes(new { style = "margin-left:0" }))
.DataBinding(dataBinding => dataBinding.Ajax()
.Insert("InsertAccount", "Administration")
.Update("SaveAccount", "Administration")
.Delete("DeleteAccount", "Administration"))
.DataKeys(keys => { keys.Add(a => a.AccountId); })
.Columns(columns =>
{
columns.ForeignKey(b => b.BankId, (IEnumerable)ViewData["Banks"], "ID", "Name").Width(50);
columns.Bound(a => a.AccountNumber).Width(110);
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Image);
commands.Delete().ButtonType(GridButtonType.Image);
}).Width(16);
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Pageable()
.Scrollable()
.Sortable()
)
Controller:
[GridAction]
public ActionResult Accounts()
{
ViewData["Banks"] = db.Banks.Select(b => new { Id = b.BankId, Name = b.Name });
return View(new GridModel(accountRepository.All()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult InsertAccount()
{
//Create a new instance of the EditableProduct class.
EditableAccount account = new EditableAccount();
//Perform model binding (fill the product properties and validate it).
if (TryUpdateModel(account))
{
//The model is valid - insert the product.
accountRepository.Insert(account);
}
//Rebind the grid
return View(new GridModel(accountRepository.All()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult SaveAccount(int id, int bankId)
{
EditableAccount account = new EditableAccount
{
AccountId = id,
Bank = db.Banks
.Where(b => b.BankId == bankId)
.Select(b => b.Name).SingleOrDefault(),
BankId = bankId
};
TryUpdateModel(account);
accountRepository.Update(account);
return View(new GridModel(accountRepository.All()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult DeleteAccount(int id)
{
//Find a customer with ProductID equal to the id action parameter
EditableAccount account = accountRepository.One(a => a.AccountId == id);
if (account != null)
{
//Delete the record
accountRepository.Delete(account);
}
//Rebind the grid
return View(new GridModel(accountRepository.All()));
}
Model:
public class EditableAccount
{
[ScaffoldColumn(false)]
public int AccountId { get; set; }
[Required]
[UIHint("GridForeignKey")]
[DisplayName("Bank")]
public int BankId { get; set; }
public string Bank { get; set; }
[Required]
[DisplayName("AccountNumber")]
public int AccountNumber { get; set; }
}
Repository:
public IList<EditableAccount> All()
{
IList<EditableAccount> result =
(from account in db.Accounts
select new EditableAccount
{
AccountId = account.AccountId,
Bank = account.Bank.Name,
BankId = account.BankId,
AccountNumber = account.AccountNr
}).ToList();
return result;
}
public EditableAccount One(Func<EditableAccount, bool> predicate)
{
return All().Where(predicate).FirstOrDefault();
}
public void Insert(EditableAccount insertedAccount)
{
Account account = new Account();
account.BankId = insertedAccount.BankId;
account.AccountNr = insertedAccount.AccountNumber;
db.Accounts.InsertOnSubmit(account);
db.SubmitChanges();
}
public void Update(EditableAccount updatedAccount)
{
Account account = db.Accounts.SingleOrDefault(a => a.AccountId == updatedAccount.AccountId);
account.BankId = updatedAccount.BankId;
account.AccountNr = updatedAccount.AccountNumber;
db.SubmitChanges();
}
public void Delete(EditableAccount deletedAccount)
{
Account account = db.Accounts.SingleOrDefault(a => a.AccountId == deletedAccount.AccountId);
db.Accounts.DeleteOnSubmit(account);
db.SubmitChanges();
}
Someone answered my question on the Telerik forums:
http://www.telerik.com/community/forums/aspnet-ajax/grid/asp-net-mvc-razor-grid-with-editable-foreign-key-dropdown-column.aspx

Add css class to row in MVCContrib grid

I'm displaying a grid of data, and one of the attributes is an expiration date. If the expiration date is less than 60 days away, I'd like to highlight the row.
I found this post, and used the answer there to use the RowAttributes function:
#Html.Grid(Model.PagedList).Columns(column =>{
column.For(m => m.Name);
column.For(m => m.ExpirationDate);
}).Sort(Model.GridSortOptions)
.Attributes(#class => "grid")
.RowAttributes(m => new MvcContrib.Hash(#class =>
(m.Item.ExpirationDate.Value.AddDays(-60) < DateTime.Now)) ? "warning" : "")
But I get a compilation error saying:
Cannot implicitly convert type 'MvcContrib.Hash' to 'bool'
What am I doing wrong here?
The following works fine for me:
Model:
public class MyViewModel
{
public DateTime? ExpirationDate { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { ExpirationDate = DateTime.Now.AddDays(70) },
new MyViewModel { ExpirationDate = DateTime.Now.AddDays(30) },
new MyViewModel { ExpirationDate = DateTime.Now.AddDays(90) },
};
return View(model);
}
}
View:
#using MvcContrib.UI.Grid
#using MvcContrib
#model IEnumerable<MyViewModel>
#(Html
.Grid(Model)
.Columns(column => {
column.For(m => m.ExpirationDate);
})
.Attributes(#class => "grid")
.RowAttributes(m => new Hash(#class => (m.Item.ExpirationDate.Value.AddDays(-60) < DateTime.Now) ? "warning" : "" ))
)
You could also write an extension method for your model:
public static class RowAttributesExtensions
{
public static Hash GetRowAttributes(this MyViewModel model)
{
return new Hash(#class => (model.ExpirationDate.Value.AddDays(-60) < DateTime.Now) ? "warning" : "");
}
}
and then:
#(Html
.Grid(Model)
.Columns(column => {
column.For(m => m.ExpirationDate);
})
.Attributes(#class => "grid")
.RowAttributes(m => m.Item.GetRowAttributes())
)
which makes it more readable.

Resources