Add css class to row in MVCContrib grid - asp.net

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.

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))

Kendo Grid AJAX Bound Not Updating MVC4

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.

Why jQuery code not called here...please suggest?

Below all my code,
*Model *
Below is Model code,
public class MyViewModel
{
public int? Year { get; set; }
public int? Month { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(2000, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
Controller
Below is Controller code,
//
// GET: /MenuSix/
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
public ActionResult Months(int year)
{
if (year == 2011)
{
return Json(
Enumerable.Range(1, 3).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
return Json(
Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
View
Below is View code,
#model DemoWeb.Models.MenuSix.MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.Year,
new SelectList(Model.Years, "Value", "Text"),
"-- select year --"
)
#Html.DropDownListFor(
x => x.Month,
Enumerable.Empty<SelectListItem>(),
"-- select month --"
)
}
#section PageScriptsAndCSS{
<script type="text/javascript">
$('#Year').change(function () {
debugger;
var selectedYear = $(this).val();
if (selectedYear != null && selectedYear != '') {
$.getJSON('#Url.Action("Months")', { year: selectedYear },
function (months) {
var monthsSelect = $('#Month');
monthsSelect.empty();
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text
}));
});
});
}
});
</script>
}
I'm testing above code, but in jquery code not called here, please suggest why the dropdown change event not called in jquery?
Wrap the javascript code in document.ready to ensure that control is available when binding then event. IT looks this javascript is rendered at the head and at that point drop down is not yet added to the DOM
$(document).ready(function()
{
$("#year").///rest of the code
});

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

Checkbox not set in ASP.NET MVC 3

I'm trying to initialize my checkbox in controller like the code below, but in the view it's not selected whether it's true or false
controller :
foreach (var item in AssignedUsers)
{
if (dc.App_UserTasks.Any(u => u.UserId == item.UserId && u.TaskId == ProjectTask.Id))
{
Users.Single(u => u.Id == item.Id).IsChecked = true;
}
else
{
Users.Single(u => u.Id == item.Id).IsChecked = false;
}
}
view:
#for (int i = 0; i < Model.Responsibles.Count; i++)
{
#Html.CheckBoxFor(u => u.Responsibles[i].IsChecked)
}
send model from controller to view :
var EPT = new EditProjectTaskModel
{
ProjectId = ProjectTask.ProjectId,
Title = ProjectTask.Title,
ProjectName = ProjectTask.App_Project.ProjectName,
Id = ProjectTask.Id,
Description = ProjectTask.Description,
EstimatedTime = ProjectTask.EstimatedTime,
Status = ProjectTask.Status,
Responsibles = Users.ToList()
};
return PartialView("_EditProjectTask", EPT);
Assuming your User ViewModel looks like this
public class UserViewModel
{
public string Name { set;get;}
public int UserId { set;get;}
public bool IsSelected { set;get;}
}
And you have your main view model has a collection of this UserViewModel
public class EditProjectTaskModel
{
public List<UserViewModel > Responsibles { set; get; }
public EditProjectTaskModel()
{
if(this.Responsibles ==null)
this.Responsibles =new List<UserViewModel >();
}
}
Create an editor template called Responsibles.cshtml with the below content
#model YourNameSpace.UserViewModel
#Html.CheckBoxFor(x => x.IsSelected)
#Html.LabelFor(x => x.IsSelected, Model.Name)
#Html.HiddenFor(x => x.UserId)
Now include that in your main view like this, instead of the loop
#model EditProjectTaskModel
#using (Html.BeginForm())
{
//other elements
#Html.EditorFor(m=>m.Responsibles)
<input type="submit" value="Save" />
}
If you want to get the selected checkboxes on a form submit.
[HttpPost]
public ActionResult Save(EditProjectTaskModel model)
{
List<int> userIDs=new List<int>();
foreach (UserViewModel user in model.Responsibles)
{
if (user.IsSelected)
{
//you can get the selected user id's here
userIDs.Add(user.UserId);
}
}
}

Resources