MvcContrib grid conditional cell formatting based on model value - mvccontrib-grid

I need to conditional formatting a cell value based on a boolean value in the model.
I have the column col.For(item => item.Detail);
If item.Unfinished I need to apply some css style
How can I do that?

The answer is in my comment to the original post:
http://groups.google.com/group/mvccontrib-discuss/browse_thread/thread/f872d298cc9d53dc
column.For(x => x.Surname).Attributes(x => {
if(x.Item.Surname == "foo") {
return new Dictionary<string, object> { { "style", "color:red"} };
}
return new Dictionary<string, object>();
});

if you still looking for solution:
"
The above property of the MVCContrib grid also does the trick.
<%= Html.Grid(Model.Services).AutoGenerateColumns()
.Columns(column => {
column.For(a => Html.ActionLink("Editar", "Edit", new { id = a.Id }))
.InsertAt(0).Encode(false)
.CellCondition(x =>
(x.CreatedBy==Membership.GetUser().UserName));
})
.Sort(Model.GridSortOptions)
.Attributes(#class => "table-list")
.Empty(Resources.NO_DATA_TO_DISPLAY)
%>
"
Credits to Jeremy Skinner
http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/comment-page-1/#comment-19059
and jpassos who originally posted it here:
http://forums.asp.net/p/1559843/3850767.aspx

Related

FlatList single select cell

I followed the example from official docs, here is how to implement multiselection feature:
state = { selected: (new Map(): Map<string, boolean>) };
onPressItem = (id) => {
this.setState((state) => {
const selected = new Map(state.selected);
selected.set(id, !selected.get(id));
return { selected };
});
};
I'm struggling with making it single select though. It's easy to return new Map with false values anytime cell is tapped, but that means the cell cannot be deselected by another tap on it, which is the desired feature in my case.
onPressItem = (id) => {
this.setState((state) => {
const selected = new Map();
selected.set(id, !selected.get(id));
return { selected };
});
};
How would you implement it? Should I use lodash to iterate over the Map to find the one that already is true and change its value (now sure how to iterate over Map though), or maybe there is some better approach I am missing right now?
EDIT
Iterating over elements of the selected Map seems to be a really ugly idea, but it is simple and it actually works. Is there any better way to do it that I am missing out on?
onPressItem = (id: string) => {
this.setState((state) => {
const selected = new Map(state.selected);
selected.set(id, !selected.get(id));
for (const key of selected.keys()) {
if (key !== id) {
selected.set(key, false);
}
}
return { selected };
});
};
Thanks in advance
You can just set only one value instead of a map like this
onPressItem = (id) => {
this.setState((state) => {
const selected = selected === id ? null : id;
return { selected };
});
};
I had the same issue, my solution was:
_onPressItem = (id: string) => {
// updater functions are preferred for transactional updates
this.setState((state) => {
// copy the map rather than modifying state.
const selected = new Map(state.selected);
// save selected value
let isSelected = selected.get(id);
// reset all to false
selected.forEach((value, key) => {
selected.set(key, false);
});
// then only activate the selected
selected.set(id, !isSelected);
return { selected };
});
};

Custom is Obsolete

I updated a project to the latest version of Fluent Validation and I get a warning:
'AbstractValidator<AccountSignInModel>.Custom(Func<AccountSignInModel, ValidationFailure>)'
is obsolete: 'Use model-level RuleFor(x => x) instead'
When I am using the following code:
When(x => !String.IsNullOrEmpty(x.Password) && !String.IsNullOrEmpty(x.Username), () => {
Custom(x => {
Boolean valid = service.ValidateCredentials(x.Username, x.Password));
if (!valid)
return new ValidationFailure("Credentials", "Authentication failed");
return null;
});
});
I don't know how to convert this into a RuleFor(x => x).
Or is there another alternative to custom?
We decided to use Fluent Validation recently on our application. So I am fairly new to this, figuring stuff as we go forward.
Stumbled upon your issue while searching for a different issue. There are not many resources on this. Thought I would share my thoughts, if it can help you.
Here is what I would do.
public NewCustomValidator(Interface int)
{
CascadeMode = CascadeMode.Continue; // you could use StopOnFirstFailure or Continue
RuleFor(x=> x.UserName).NotEmpty(); // Will return an error if null or empty
RuleFor(x=> x.Password).NotEmpty();
RuleSet("SomeNameHere", () =>
{
CascadeMode = CascadeMode.StopOnFirstFailure;
var isValid = false;
RuleFor(x=> new { x.UserName, x.Password })
.Must((u , p) =>
{
valid = ValidateCredentials(u, p);
return valid;
})
.WithMessage("You can show any message if you want");
RuleFor(x => x.UserName).Must((s) => isValid);
RuleFor(x => x.Password).Must((s) => isValid);
});
}
So, I am basically using your method to define in a Rule Set. You may have to add some code to validate the ruleSet.
var result = validator.Validate(NewCustom, ruleSet: "SomeNameHere");
Disclaimer: This code may not compile. But it will give you an idea on how to approach the problem. If you have better ideas or If you could make the code work, please post the answer. That will help me gain some more knowledge. Thanks.

Kendo Grid Custom comboBox Filter

I has grid which will load data as filterable combo box, So I need to create custom filter for this column with filterable combo box also.
I create combo box and assign it to the column filter UI. My problem is when the combobox read the data from the controller it does not send the filter text to the controller.
<script type="text/javascript">
function outletFilter(element) {
debugger;
element.kendoComboBox({
dataTextField: "OutletNameE",
dataValueField: "OutletID",
autoBind: false,
minLength: 1,
dataSource: {
serverFiltering: true,
transport: {
read: "#Url.Action("GetOutletsCombo")"
}
},
optionLabel: "--Select Value--"
});
}
</script>
#(Html.Kendo().Grid<Spine.ERP.ViewModel.AccountReceivableOutletViewModel>()
.Name("ARDetails_OutletGrid")
.Columns(columns =>
{
columns.Bound(p => p.AccountReceivableID).Hidden();
columns.Bound(p => p.AccountReceivableOutletID);
columns.Bound("Outlet.OutletName")
.EditorTemplateName("OutletForeignKeyEditor")
.ClientTemplate("<a>#=OutletID ##=OutletID? '-' : ' ' ##=OutletID ?
Outlet.OutletName : ' ' #</a>")
.Filterable(filter => filter.UI("outletFilter"));
})
And here are my controller function
public ActionResult GetOutletsCombo(string text)
{
if (text == null)
text = "";
var result = new List<OutletViewModel>();
var Outlets = outletRepository.FilterOnID("Outlet", new string[] { "OutletID", "OutletNameE" }, text).ToList();
result = (from outlet in Outlets
select new OutletViewModel
{
OutletID = outlet.OutletID,
OutletNameE = outlet.OutletNameE,
OutletNameA = outlet.OutletNameA
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
First of all if you perform a "read", it does not send any additional value to the controller so in "public ActionResult GetOutletsCombo(string text)" you wouldn't get any value in "text".
For server filtering you can see kendo's demo on the following page
http://demos.kendoui.com/web/combobox/serverfiltering.html
As far as I get from your question, you want to do a Kendo Grid and on there you want to have a combobox to filter the data in the grid. In this case, you may check the similar kind of demo in Kendo's site
http://demos.kendoui.com/web/grid/toolbar-template.html
For filter menu you can check this on kendo under ASP.NET MVC
http://demos.kendoui.com/web/grid/filter-menu-customization.html
Hope you can work out your problem from these examples. In case you can't then put a comment underneath this post. I shall try again to help you.

Download pdf files from kendo ui grid

I have a table column called PDF(varbinary). The column will bind in kendo ui grid as hyperlink which download the pdf from the database.
The following is the code that i have so far. Based on the research i have done. Therefore i am implementing a template.
The italic code below showing said error "required )" and i am not quite sure what i am missing here.
columns.Template(#).ClientTemplate("Download file").Title("Download1");
Therefore I would kindly advise to implement the download file (pdf format) in kendo ui grid. Thank you
#(Html.Kendo().Grid<HH.Models.OrderModel>()
.Name("OrderGrid")
.HtmlAttributes(new { #Style = "align:center; font-size:10px; width:600px" })
.Columns(columns =>
{
columns.Bound(p => p.OrderId);
columns.Bound(p => p.Date).EditorTemplateName("Date").Format("{0:dd/MM/yyyy}");
columns.Bound(p => p.CustFullName).Width(120);
columns.Template(#<text></text>).ClientTemplate("Download file").Title("Download1");
columns.Template(#<text></text>).ClientTemplate("" + Html.ActionLink("<img src='" + Url.Content("~/Content/icons/pdficon_small.png") + "' />", "DocumentDownload2", "Administration", new { id = "#=OrderId#" }, null) + "").Title("Download2");
})
.ToolBar(toolbar => toolbar.Save().Text("Save Changes"))
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Selectable()
.Pageable(paging => paging
.Input(false)
.Numeric(true)
.PreviousNext(true)
.PageSizes(new int[] { 5, 10, 25, 50 })
.Refresh(false)
)
.DataSource(dataSource => dataSource
.Ajax()//bind with Ajax instead server bind
.PageSize(10)
.ServerOperation(true)
.Model(model =>
{
model.Id(p => p.OrderId);
})
.Read(read => read.Action("GetOrder", "Administration").Type(HttpVerbs.Get))
.Update("EditOrder", "Administration")
)
)
**controller**
public ActionResult Download1()
{
string contentType = "application/pdf";
string filePath = Server.MapPath("~/Files/OrderDetails.pdf");
return File(filePath, contentType, "OrderDetails.pdf");
}
public ActionResult Download2(int orderId)
{
string contentType = "application/xlsx";
string filePath = Server.MapPath("~/Files/OrderDetails.pdf");
return File(filePath, contentType, "OrderDetails.pdf_" + orderId.ToString() + ".xlsx");
}
You can't implement the PDF download on the client-side easily. You should instead stream the PDF file using another action method. You can check this question for some ideas: Retrieve and display image from database using ASP.Net MVC
The grid should contain a link to this action method:
.ClientTemplate("<a href='/administration/getpdf?orderid=#= OrderID #'>get pdf</a>");
public ActionResult GetPdf(int orderID)
{
// find the pdf by orderid
return File(stream, "application/pdf", "DownloadName.pdf");
}
You'd have to implement this yourself. KendoUI is a client-side technology, and has nothing to do with serving an arbitary PDF from a datasource.
If you'd like to generate a PDF, look up the following resources:
PDF:
http://www.kendoui.com/code-library/mvc/grid/export-grid-to-pdf.aspx
Maybe this UserVoice entry:
http://feedback.kendoui.com/forums/127393-kendo-ui-feedback/suggestions/3494585-kendoui-mvc-serverside-wrappers-should-allow-expor
The available answers seem to be outdated. There are new developments in this area. Please check this example and also telerik api reference . Hope it helps in the future.
Another way to do the same thing, with ActionLink inside the ClientTemplate:
columns.Template(#<text>
#Html.ActionLink("get pdf", "getpdf", "administration", new { orderid= #item.OrderId}, null)
</text>);
As taken from: http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/faq#how-do-i-use-action-links

gmaps4rails - Drop a marker and update fields attribute in a form

I'm trying to implement this, from the gem wiki https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Javascript-goodies
<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
var markersArray = [];
// On click, clear markers, place a new one, update coordinates in the form
Gmaps.map.callback = function() {
google.maps.event.addListener(Gmaps.map.map, 'click', function(event) {
clearOverlays();
placeMarker(event.latLng);
updateFormLocation(event.latLng);
});
};
// Update form attributes with given coordinates
function updateFormLocation(latLng) {
$('location_attributes_latitude').value = latLng.lat();
$('location_attributes_longitude').value = latLng.lng();
$('location_attributes_gmaps_zoom').value = Gmaps.map.map.getZoom();
}
// Add a marker with an open infowindow
function placeMarker(latLng) {
var marker = new google.maps.Marker({
position: latLng,
map: Gmaps.map.map,
draggable: true
});
markersArray.push(marker);
// Set and open infowindow
var infowindow = new google.maps.InfoWindow({
content: '<div class="popup"><h2>Awesome!</h2><p>Drag me and adjust the zoom level.</p>'
});
infowindow.open(Gmaps.map.map,marker);
// Listen to drag & drop
google.maps.event.addListener(marker, 'dragend', function() {
updateFormLocation(this.getPosition());
});
}
// Removes the overlays from the map
function clearOverlays() {
if (markersArray) {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
markersArray.length = 0;
}
</script>
<% end %>
But with no luck...I'm guessing its more of an issue with the name/id of my field(s), pardon my javascript knowledge.
I've changed the fields to update with the coordinates:
function updateFormLocation(latLng) {
$('location[lat]').value = latLng.lat();
...
}
But the field doesn't get updated:
= simple_form_for :location do |l|
= l.input :lat
...
Am I missing something? Thanks!
By the look of it, that syntax is written for prototype. If you're using rails 3.1 with jQuery, you'll need to update that syntax to find your DOM nodes.
i.e. if you're looking for an element with id "location_attributes_latitude", you need to use:
$('#location_attributes_latitude')
And in order to set the value:
$('#location_attributes_latitude').val(latLng.lat());
If you only need to drop an update exist marker, just only need to do this
location_gmaps = () ->
Gmaps.map.callback = () ->
google.maps.event.addListener Gmaps.map.markers[0].serviceObject, 'dragend', (event) ->
updateFormLocationEventos(event.latLng)
# Update form attributes with given coordinates
updateFormLocationEventos = (point) ->
$('#event_position_latitude').val(point.lat())
$('#event_position_longuitude').val(point.lng())
I hope this help you