Change the background color of the first row in Helper WebGrid MVC without JQuery - model-view-controller

I would like to change the background color of the first row in a WebHelper WebGrid for MVC without the use of JQuery.
Any Thoughts?

#model IEnumerable<MyViewModel>
#{
var indexedModel = Model.Select((item, index) => new { Element = item, Index = index });
var grid = new WebGrid(indexedModel);
}
#grid.GetHtml(
columns: grid.Columns(
grid.Column(
columnName: "item.MyProperty",
header: "Myproperty",
format:
#<text>
<div#Html.Raw(item.Index == 0 ? " class=\"firstRow\"" : "")>
#item.Element.MyProperty
</div>
</text>
)
)
)
and in your CSS:
.firstRow {
background-color: Red;
}

One suggestion could be in each columns's format parameter, use an if-else situation based on a distinct variable that will wrap the data in a span with a css. A bit cumbersome but should work.
For this reason some JQuery would potentially be easier.

Related

Using a custom window with ajax form to add new grid row

I need to create a more advanced method of adding new elements to a kendo grid, so in short I have replicated the following example as it does exactly what I needed:
https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/window/KendoWindow-Ajax-Form
And it works just fine. Only difference is the new row is added in it's correct spot in the grid, and not on the top as per usual. How can I, using the example linked to, place the new row on the top?
(I'm thinking it's not necessary to show my code here as it very closely resembles the code given in the link above)
So If you want to add a row up top I am thinking you could use a custom template. I may not be very clear on what you are doing but , I will attempt to help you.
Here is the grid in the code:`
#(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Message).EditorTemplateName("MessageEditor");
}
.DataSource(datasource => datasource
.Ajax()
.Read(read => read.Action("GetOrders", "OrdersData"))
)
)`
Then write the template like this:
<script type="text/x-kendo-template" id="MessageEditor">
<div class="k-header k-grid-toolbar">
<div style="display: inline-block; font-size:1.25em; padding:
</div>
</div>
</script>
Well this may not be the best solution , however it is the only way I know to create a custom column in a Kendo grid
Ended up finding the solution myself eventually. Going by the example in the link I made in the original post, this is what I did:
Firstly when a new "order" is made, I make sure that the model returned in the "Create" method in OrdersDataController has an ID from when the model is added to the DB.
So when this part gets executed in "_OrdersCreate.cshtml":
#if (Model != null && ViewData.ModelState.IsValid)
{
<script>
closeCreatePopup();
</script>
}
I send information on the new Order created. So to that end I have modified "closeCreatePopup()" to handle arguments.
So for the finished results I will just use a piece of code from my own project, the following is my implementation of "closeCreatePopup()":
function closeCreateEmployeeWindow(name, rHPersonID, personID, organizationID) {
if (name !== undefined
&& rHPersonID !== undefined
&& personID !== undefined
&& organizationID !== undefined) {
var grid = $("#grid").data("kendoGrid");
grid.dataSource.insert({ Name: name, RHPersonID: rHPersonID, PersonID: personID, OrganizationID: organizationID });
grid.dataSource.sync();
}
var wnd = $("#createEmployeeModal").data("kendoWindow");
wnd.refresh({ url: '#Url.Action("CreateEmployee", "Employee", new { Area = "Administration" })' });
wnd.close();
}
The important part is this:
var grid = $("#grid").data("kendoGrid");
grid.dataSource.insert({ Name: name, RHPersonID: rHPersonID, PersonID: personID, OrganizationID: organizationID });
grid.dataSource.sync();
What is happening here is I use the "insert" method from the grid, and add a new object. "Insert" inserts the new object to the very top of the grid. Remember to call the "sync" method right after.
By doing it like this, the normal "create" method built into the grid is replicated.

What would be the type of item in MVC4 WebGrid

I am using webgrid to displat list of records.
My view is tightly coupled with IEnumerable.
#model IEnumerable<Models.SitesConfig.Configuration>
I am binding webgrid with Model.
var grid = new WebGrid(Model, rowsPerPage: 50);
I am trying to format a column using #helper method. #helper method taking a parametr of type Models.SitesConfig.Configuration.
When I try to load the view, I am getting invalid arguments error.
This is my view.
#model IEnumerable<Models.SitesConfig.SiteConfiguration>
#section Styles {
<link href="#Url.Content("~/Content/SatelliteSite.css")" rel="stylesheet" type="text/css" />
}
#{
ViewBag.Title = "List of Satellite Sites";
}
#helper FormatTemplateColors(Models.SitesConfig.SiteConfiguration item)
{
#String.Format(
"Border: {0} <br/>Link: {1} <br/>Text: {2}",
item.BorderColor != null ? item.BorderColor.Name : string.Empty,
item.LinkColor != null ? item.LinkColor.Name : string.Empty,
item.TextColor != null ? item.TextColor.Name : string.Empty)
}
#{
var grid = new WebGrid(Model, rowsPerPage: 50);
}
<div>
#grid.GetHtml(columns: grid.Columns(
grid.Column("Template",
style: "color-column-width",
format:(item) => #FormatTemplateColors(item)
)
)
</div>
Can somebody help me on this.
In the format lambda the item parameter is an instance of the WebGridRow class (in a form of dynamic) where the Value property holds the actual item.
So you need to write:
format:(item) => #FormatTemplateColors(item.Value)
SideNote if you wan't to output html you need to use the Html.Raw helper. So modify your helper to:
#helper FormatTemplateColors(Models.SitesConfig.SiteConfiguration item)
{
#Html.Raw(String.Format(...
}

MVC3 WebGrid: Can htmlAttributes be used on rows/columns?

I'm using a WebGrid to create a paged/sortable list in MVC3. I've created an AJAX enabled Delete button which makes the delete call via AJAX, after which I'd like it to remove the row from the table.
The way I'd like to achieve this is by having an id or data-id attribute on the <tr> in the table so that I can easily manipulate it using jQuery. However I can't work out how to add attributes to rows when using a WebGrid.
I know that attributes can easily set at the grid level like so:
#grid.GetHtml(htmlAttributes: new { id = "gridMapping", style = "width:100%;" },
However I don't know how to achieve the same at the row/column level.
#grid.GetHtml(
columns: grid.Columns(
grid.Column(format: (item) => Html.CheckBox("SelectedInvoice",new { value=item.transactionId})),
//// rest of your columns here
)
)
so one way would be putting an HTML helper method in place that can handle your htmlAttributes.
Other way - using combination of format: and Html.Raw
And the last, but may be the easiest: javascript (jQuery)
so you can try something like :
$('#grid tr').each(function(){
$(this).attr('yourhtmlattribute','value');
});
and in similar way for TDs.
Here is how I achieved this
In your webgrid set up add this to one of the colums.
grid.Column("UserName", "User Name", format: #<text><span data-id='#item.Id'>#item.UserName</span></text>, canSort: true),
No when the HTML grid is rendered you will get this.
<tr jQuery45435434="3"> <span data-userid="1">Fred Smith</span></tr>
<tr jQuery45435434="4"> <span data-userid="2">Sally Smith</span></tr>
<tr jQuery45435434="5"> <span data-userid="3">Joe Smith</span></tr>

#Html.DropDownList width

Q: How to set width for #Html.DropDownList (and not in css)?
#Html.DropDownList("ListId", String.Empty, new {style="width: 250px;"}) #* no go!*#
The second argument of the DropDownList helper must be an IEnumerable<SelectListItem>. You are passing a string (an empty one to be more precise). So in order to use this helper you will have to respect its signature:
#Html.DropDownList(
"ListId",
Enumerable.Empty<SelectListItem>(),
new { style = "width: 250px;" }
)
Obviously generating an empty dropdown list is of little use. You probably have a view model (you should by the way) that you want to use to bind to:
#Html.DropDownList(
"ListId",
Model.MyList,
new { style = "width: 250px;" }
)
and of course because you have a view model you should prefer to use the DropDownListFor helper:
#Html.DropDownListFor(
x => x.ListId,
Model.MyList,
new { style = "width: 250px;" }
)
and finally to avoid cluttering your HTML with styles you should use an external CSS:
#Html.DropDownListFor(
x => x.ListId,
Model.MyList,
new { #class = "mycombo" }
)
where in your external CSS you would define the .mycombo rule:
.mycombo {
width: 250px;
}
Now you have what I consider a proper code.
You should use the View Model approach. However the lazy way out is just to give the 2nd parameter a null.
#Html.DropDownList("ListId", null, new {style="width: 250px;"})
#Html.DropDownListFor(model => model.Test,
new SelectList(new List<YourNamespace.Modelname>(), "Id", "Name"),
null, new { #id = "ddlTest", #style="width: 250px;" })
There is a jquery technique that allows you to set the width without having to deal with the #Html.DropDownList constructor.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#ListId").width(300);
});
</script>

ASP.NET MVC 3 WebGrid - Conditional Column Formatting

Is there anyway to do conditional formatting with Webgrid in ASP.NET MVC 3?
I know I can say:
... grid.Column("PropertyName", "Header Name", style: "bold") ...
and it will render HTML that for the TD that says: class="bold".
What I want, is to render some TDs in one style and other TDs in another style. Like:
... grid.Column("PropertyName", "Header Name", style: (item) => (item.Property > 100) ? "bold" : "normal")) ....
but this causes the error "Best overloaded method match ... has some invalid arguments."
Any idea if this is possible?
Thanks
.Jim Biddison
I know I'm kind of late with the answer, but if someone is still looking for that kind of conditional formating / column value binding for WebGrid here's somehting that works :
#grid.GetHtml(
columns: grid.Columns(
grid.Column(format: (item) => (item.someproperty !=null) ?
Html.Raw("I've got value") :
Html.Raw("I don't :("))
)
)
You can do this with some JQuery:
<script type='text/javascript'>
$(document).ready(function () {
jQuery.each($('tbody tr td'), function () {
if (this.textContent == "some value") {
$(this).addClass("some class");
}
});
});
</script>
Of course, you'll have to modify the logic inside the each loop...
Hope that helps.
I don't think the style property accepts functions. You can use jQuery or here is a hack:
Hack
For googler, an improved version of the Torm answer:
#grid.GetHtml(
columns: new[]
{
grid.Column(format:item => Html.Raw("<span" + (item.Property > 100 ? " style='bold'" : "") + ">" + item.Property + "</span>")),
}
)

Resources