Is there an equivalent for the following?
// convert model to dynamic (this is how the model is coming in)
IEnumerable<dynamic> dynmodel = (IEnumerable < dynamic >)Model;
// dynamic lambda ???
string col = "x.Name";
var grid = new WebGrid(source: dynmodel.OrderBy(x => #col)); // Doesn't resolve but need an equivalent here!!!
There is a project out there called Dynamic LINQ.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Related
I need to unit test the controllers method results with the following code
StoreController test = new MvcMusicStore.Controllers.StoreController();
ActionResult result = test.Index();
ViewResult p = (ViewResult)result;
result and p shows 10 items in the model when debugging but it seems that I can not do Count or foreach to check how many records are returned as both objects are dictionary.
How can this be done?
Thanks
ViewResult.Model is of type object you have to cast it to the collection type first to get a count.
For example, if you're passing the list of integers as a model to your view, you can get the count this way:
var model = p.Model;
var list = model as List<int>();
var count = list.Count;
Assuming you have a model of IEnumerable<DataType> and you want to get this model in a unit test, you have to cast the result.ViewData.Model to your type and then do your Assertions:
var test = new StoreController();
var result = test.Index() as ViewResult;
var data = (IEnumerable<ModelType>) result.ViewData.Model;
Assert.AreEqual(10, data.Count());
Reference: https://www.asp.net/mvc/overview/older-versions-1/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs (Listing 4)
This is my Query =>
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment");
I want to display the values in variable Department in ViewBag or Anywhere.How can I do that?
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment").ToList()
and then work with list
You can use linq to Entities without executing raw queries as:
var department = dataContext.Department.Select(x=>x.Id).ToList();
If you are stubborn to use raw query, you can use as teo van kot has suggested above:
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment").ToList();
You can assign the list to ViewBag in controller as:
ViewBag.DepartmentIDs = department;
You can display the values in View as:
#{
foreach(var item in ViewBag.DepartmentIDs)
{
<span>#item <br/></span>
}
}
I have a SQL table with between 8 and 9 records that hold background configurations for my home page.
I want to randomly select one of them each time the page is refreshed and I want to use a Lambda expression in my controller. Something like:
var myRandomSelect = db.MyBackgrounds.Random();
That obviously does not work, but I'm having trouble figuring it out.
Any help?
You can write a kind of extension method:
public static T GetRandom(this IList<T> source)
{
var rnd = new Random(DateTime.Now.Millisecond);
return source.Skip(rnd.Next(0, source.Count())).First();
}
use it like
var myRandomSelect = db.MyBackgrounds.GetRandom();
Assuming you are using EF
var random = db.MyBackgrounds
.OrderBy(c => Guid.NewGuid())
.FirstOrDefault();
I want to pass two values from controller action to asp.net MVC 3 Razor view. I am doing like this in action method:
var model = new { reportid = rid, refno = refernumber};
return View(model );
but when i try to access it in view like this:
#Model.reportid
I get, object doesn't contain property reportid
How can I pass multiple values without using viewbag ?
Well, i strongly recommend you to use ViewModel class. But if for some reason you have phobia of extra viewmodel classes, you can use C# feature called Tuple
var model = Tuple.Create(firstObject, secondObject)
and then your view will be of type Tuple, for example
#model Tuple<int, string>
and you can access them like this
#Model.Item1
And then you can congratulate yourself, you have achieved nice mess with hidden meaning :)
Another way to accomplish this task - is to use ExpandoObject.
dynamic model = new System.Dynamic.ExpandoObject();
model.reportid = 123
model.refno = 456;
Set the view model type to dynamic:
#model dynamic
#Model.reportid
#Model.refno
I'm sticking on how to best present some data that's being dynamically generated from two different tables.
Given my query:
var assets = assetRepo.Find(x => x.LoginId == User.Identity.Name);
var accounts = repository.Find(x => x.AccStatus == "A" && x.LoginId == User.Identity.Name);
var query = from asst in assets
join acct in accounts on asst.AccountId equals acct.AccountId
select new
{
Account = acct.AccountNumber,
Status = acct.AccStatus,
Make = asst.Make,
Model = asst.Model,
Submodel = asst.SubModel,
Registration = asst.Registration,
Balance = acct.BalanceOutstanding,
NextPayment = acct.NextPayment,
Date = String.Format("{0:dd MMM yyyy}", acct.NextPaymentDate),
Due = acct.ArrearsBal
};
What would be the best (i.e. cleanest) way to bind this to the view? Would a custom class be required or is there a way to specify and iterate over a collection of anonymous types?
Creating custom class can give you additional benefits. You can use DisplayAttribute to set column headers and order. Then you can create view (or template to use with DisplayFor) that takes list of objects of any type and uses reflection to read annotations and display view nicely.
class Report {
[Display(Name="Account",Order=1)]
public string Account {get; set;}
[Display(Name="Next payment",Order=2)]
public Date NextPayment {get; set;}
}
It looks also clean. You will be able to use this annotations not only for grid, but also for excel exports or other data operations.