formatting in razor nested webgrid - asp.net-mvc-3

I'm nesting a webgrid inside another webgrid as shown in Razor Nested WebGrid
But when I try to format the columns inside the nested webgrid it's throwing an error stating that the column in the mastergrid has invalid arguments.
Has anyone faced this problem before?
Any suggestions?
Thanks
Arnab

I guess your problem is that you tried to use the same parameter name item in the inner format parameter. You cannot use the same parameter name in nested lambda expressions. You can find here more about lambda expressions.
So you need to use a different parameter name (e.g. subItem) for the inner format:
...
#topGrid.GetHtml(columns:
topGrid.Columns(
topGrid.Column("Index"),
topGrid.Column("SubItems", format: (item) =>
{
WebGrid subGrid = subGrid = new WebGrid(item.SubItems);
return subGrid.GetHtml(
columns: subGrid.Columns(
subGrid.Column("A", format: (subItem) => string.Format("Formatted: {0}", subItem.A)),
subGrid.Column("B")
)
);
})
)
)
...

Related

Populating dropdown list with two columns from database

I'm working on MVC3 project.
At my controller I already have a code that gets the Descr column from StockClass table. After that I fill a ViewBag with this list in order to retrieve it from the view and populate the dropdown list.
Currently is working fine but only shows Descr field (obviously). What i want is populate the dropdown list with two fields (Code and Descr) in this format: "code - descr".
I tried several ways but i cannot find the way to code the #Html helper correctly.
In my controller...
var oc = dba.StockClass.OrderBy(q => q.Code).ToList();
ViewBag.OrderClass = new SelectList(oc, "StockClassId", "Descr");
In my view....
#Html.DropDownList("StockClassID", (SelectList)ViewBag.OrderClass)
Could you please help me?
I don't believe there is an HTML Helper which will do that for you, but you can get what you're after like this:
var oc = dba.StockClass
.OrderBy(q => q.Code)
.ToDictionary(q => q.StockClassId, q => q.Code + " - " + q.Descr);
ViewBag.OrderClass = new SelectList(oc, "Key", "Value");
This also has the advantage of making the uses of StockClassId, Code and Descr refactor-friendly - if you rename those properties you won't be able to compile without updating this bit of code to match.

MVC Razor Web Grid- Error

I am using MVC3 webgrid. I am displaying the data in a webgrid and before displaying the data I have to calculate the number of days between start date and end date. I am using the following code.
int noOfAbsenceDays = item.AbsEnd?(item.AbsEnd.Subtract(item.AbsStart)).Days: (item.DateTime.Now.Subtract(item.AbsStart)).Days;
It complains about this error
Cannot implicitly convert type 'System.DateTime' to 'bool'
I don't know where it is coming from?
Thanks
You can try the following code:
int noOfAbsenceDays = item.AbsEnd == null ? (item.AbsEnd.Subtract(item.AbsStart)).Days : (item.DateTime.Now.Subtract(item.AbsStart)).Days;

linq problem with distinct function

I am trying to bind distinct records to a dropdownlist. After I added distinct function of the linq query, it said "DataBinding: 'System.String' does not contain a property with the name 'Source'. " I can guarantee that that column name is 'Source'. Is that name lost when doing distinct search?
My backend code:
public IQueryable<string> GetAllSource()
{
PromotionDataContext dc = new PromotionDataContext(_connString);
var query = (from p in dc.Promotions
select p.Source).Distinct();
return query;
}
Frontend code:
PromotionDAL dal = new PromotionDAL();
ddl_Source.DataSource = dal.GetAllSource();
ddl_Source.DataTextField = "Source";
ddl_Source.DataValueField = "Source";
ddl_Source.DataBind();
Any one has a solution? Thank you in advance.
You're already selecting Source in the LINQ query, which is how the result is an IQueryable<string>. You're then also specifying Source as the property to find in each string in the databinding. Just take out the statements changing the DataTextField and DataValueField properties in databinding.
Alterantively you could remove the projection to p.Source from your query and return an IQueryable<Promotion> - but then you would get distinct promotions rather than distinct sources.
One other quick note - using query syntax isn't really helping you in your GetAllSources query. I'd just write this as:
public IQueryable<string> GetAllSource()
{
PromotionDataContext dc = new PromotionDataContext(_connString);
return dc.Promotions
.Select(p => p.Source)
.Distinct();
}
Query expressions are great for complicated queries, but when you've just got a single select or a where clause and a trivial projection, using the dot notation is simpler IMO.
You're trying to bind strings, not Promotion objects... and strings do not have Source property/field
Your method returns a set of strings, not a set of objects with properties.
If you really want to bind to a property name, you need a set of objects with properties (eg, by writing select new { Source = Source })

Dynamic Linq - no property or field exists in type 'datarow'

I am using Northwind Customers Table where I fill the dataset and get the datatable.
I am trying to use dynamic linq and want to select columnName dynamically
var qry = MyDataTable.AsEnumerable().AsQueryable().Select("new(Country)");
Right now I have hard coded country but even then I get this error
No property or field 'Country' exists in type 'datarow'
I would like to eventually change this query to take the column name dynamically.
Please help!!! thanks.
The important hint is here (in bold):
No property or field 'Country' exists
in type 'datarow'
The extension method AsEnumerable of the DataTable class returns an IEnumerable<T> where T has the type DataRow. Now the Select method of Dynamic LINQ wants to work with this type DataRow which hasn't a property Country of course.
You could try this instead:
var qry = MyDataTable.AsEnumerable().AsQueryable()
.Select("new(it[\"Country\"] as CountryAlias)");
it now represents a variable of type DataRow and you can use methods of this type and perhaps also the indexer in my example above. (Dynamic LINQ supports accessing array elements by an integer index, but I am not sure though if accessing an indexer with a string key will work.)
I've used Slauma's answer and it worked. In addition i was doing OrderBy with dynamic linq maybe this will help to someone. I'll just drop the code here.
string dynamicLinqText = $"it[\"{sortColumnName}\"] {sortDirection}"; //it["PERSON_NAME"] asc
result = result.AsEnumerable().OrderBy(dynamicLinqText).CopyToDataTable();

Showing a default value in a WebGrid when a null is present?

I've got Webgrid sourced to a EF4 entity with navigation properties (basically relationships)
If the webgrid encounters a null for that foreign key it errors out because it's looking for that object, which in this case doesn't exist.
Is it possible to catch when a column item is null and default to a value within the Webgrid helper?
I guess the follwoing code should serve your purpose if I am correctly relating to your problem. Below Trigger is the navigated entity which we will get by include in linq and we can put a check like below when this entity is null.
grid.Column("Job", format: #<text> #if (#item.Trigger !=null) { <span> Write your default code here .</span> } </text> close text tag here ),
Hope that solves your problem.
I noticed after posting 'text' is getting truncated in this forum so put text in < and > between 2 # as you can see and also close that text tag before the final ).
All the best.

Resources