Im creating an MVC 3 view from a controller. My model "MyList", contains a large number of records. When I create my model using the following linq statement:
var model = _db.MyList.GroupBy(r => r.myKey);
I'm getting the error: "The model item passed into the dictionary is of type 'System.Collections.GenericlList' 1... but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable' ...
In the view I have the following code in the first line:
#model IEnumerable<MyApp.Models.MyList>
I tried returning
return View(model.ToList());
from the controller, but no joy. What am I missing?
model.ToList() will return a List<T> where T is MyList. Your model type is straight MyList. If the var declaration you have above already returns MyList, just do return View(model).
This one was dogging me all morning. I found the answer to my question in the following post:
Linq Distinct() by name for populate a dropdown list with name and value
I basically return the following:
public static IEnumberable<MyModel> FindTheKeys(this IQueryable<MyModel> myList)
{
return myList.OrderBy(r => r.AreaKey);
}
and then performed the select as indicated in the above post.
var model = _db.MyModel.FindTheKeys().GroupBy(r => r.AreaKey).Select(g => g.First());
GroupBy returns a collection of IGrouping<TKey, TSource>, not MyList (which is strange anyways, you wouldn't have a list of a list.
It doesn't even make much sense to convert a GroupBy into a list anyways. Did you actuall mean OrderBy?
Related
I have a table 'tour2s' with 2 rows and when I do:
$tour = Tour2::find(1);
dd($tour);
it returns the tour with 'id' = 1. And it's Object.
I want to turn the object to collection of only attributes of the model, nothing else. And I know that when I use ->get() it returns collection.
But when I am trying:
$tour = Tour2::find(1)->get();
dd($tour);
It returns a collection but of all 2 tour objects (full objects, not only attributes):
I did it like:
$tour = Tour2::find(1);
$tour = collect($tour);
dd($tour);
and now it's what i what - it return a collection of only model attributes (WHAT I WANTED):
SO, my question is why when I used $tour=Tour2::find(1)->get() it returned all tours not only the one with 'id'=1 ?
Passing an array to find() will return a collection.
$tour = Tour2::find([1]);
However, it will be a collection of Tour2 objects, not only the attributes.
Then, if you want only the attributes, you could use $tour->toArray()
You could also do $tour = collect(Tour2::find(1));
And to answer your question, when you use $tour=Tour2::find(1)->get(), Laravel fetch the first tour, and then calling get() on $tour will fetch all other records, so return two tours in your case.
Ok, the main question, as i understand is: "Why when i wrote Tour2::find(1)->get() i receives collection of all records".
when you wrote Tour2::find(1) it assumes that you receive instanse of model Tour2. So we can simple write $tourInstanse->get()
If you go to \Illuminate\Database\Eloquent\Model you can see that here is no method called get() but we have a magic method __call. Look at his implementation:
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
return $this->newQuery()->$method(...$parameters);
}
So, when you call get() method on a model instance you get model`s QueryBuilder (as described in last row) and call get() method on a QueryBuilder. As a result, you receiving all records of that model Class.
I am looking for solution how to access eloquent model items by 'alias' field.
There is no problem accessing items by 'id'. But building a custom query I find myself unable to access item properties.
This piece of code works perfect
$cat = Category::find(1);
return $cat->title;
But if I am querying items with any other argument - properties are inaccessible
This code
$cat = Category::where('alias','=','vodosnab')->get();
return $cat->title;
throws an exception
Undefined property: Illuminate\Database\Eloquent\Collection::$title
Could you please help.
You already got the answer but here are some insights, when you use get() or all(), it returns a collection of model objects, which is an instance of Illuminate\Database\Eloquent\Collection, so here you'll get a Collection object
$cat = Category::where('alias','=','vodosnab')->get();
Now, you can use, $cat->first() to get the first item (Category Model) from the collection and you may also use $cat->last() to get the last item or $cat->get(1) to get the second item from the collection. These methods are available in the Collection object.
Using the first() method like Category::where('alias','=','vodosnab')->first(); will return you only a single (the first mathing item) model which is an instance of your Category model. So, use all() or get() to get a collection of model objects and you can loop through the collection like:
foreach(Category::all() as $cat) { // or Category::get()
$cat->propertyName;
}
Or you may use:
$categories = Category::where('alias','=','vodosnab')->get();
foreach($categories as $category) {
$category->propertyName;
}
Also, you may use:
$categories = Category::where('alias','=','vodosnab')->get();
$firstModel = $categories->first();
$lastModel = $categories->last();
$thirdModel = $categories->get(2); // 0 is first
If you need to get only one then you may directly use:
$category = Category::where('alias','=','vodosnab')->first();
$category->fieldname;
Remember that, if you use get() you'll get a collection of Model objects even if there is only one record available in the database. So, in your example here:
$cat = Category::where('alias','=','vodosnab')->get();
return $cat->title;
You are trying to get a property from the Collection object and if you want you may use:
$cat = Category::where('alias','=','vodosnab')->get();
return $cat->first()->title; // first item/Category model's title
return $cat->last()->title; // last item/Category model's title
return $cat->get(0)->title; // first item/Category model's title
You may read this article written on Laravel's Collection object.
get() returns a Collection of items. You probably need first() that returns a single item.
I have Custom query Result as
public ActionResult Index()
{
var Query = (from E in db.SITE_MASTER.AsEnumerable()
where E.IS_PAGE == true
select new
{
E.POST_TITLE,
E.POST_TEXT
}).ToList();
return View(Query);
}
Now,
How can I make view for this result or How can I create View for this Result Query.
Thanks...
You can pass an anonymous type as a model, but please don't. It's ugly and will lead to maintenance problems.
As an alternative either use the ViewBag or create concrete type and pass that.
I need to create a linq statement that combines 2 tables and send that to the view.
Do I need to create a ViewModel for this.
Say the output will be the following
Table1.Vendor Table1.VendorName Table2.Address
It depends what your result type is.
If you return a dynamic object an anonymous type then you can't put that into the ViewBag directly (see: Stuffing an anonymous type in ViewBag causing model binder issues). But if you're returning something that's strongly typed, you can just put that straight into the ViewBag and bypass having a model.
That said, I'd always lean towards having a strongly typed model!
Yes You Should use View-model because if u want to send more than one table you may
use ViewBag or something equivalent viewdata[] that's wrong etc..
Because ViewBag for example is dynamic type it can't be sent to view with 2 table
For example if you do something like this
ViewBag.Workers=db.Workers.Join(idb.AspNetUsers, e => e.UserID, i => i.Id, (e, i) => new { UserName = i.UserName, SBIN = e.SBIN, }).ToList();
You will Get error 500 when you use this viewbag in your View
<span>#ViewBag.Workers.Anything</span>
Even in this example you should use for-each you still get error becausethe ViewBag is internal
So You could use something like that in the controller for this issue
var Workers=db.Workers.Join(idb.AspNetUsers, e => e.UserID, i => i.Id, (e, i) => new WorkerViewCardModelcs{ UserName = i.UserName, SBIN = e.SBIN, }).ToList();
return PartialView("_WorkerCard", Workers);
and Don't for get to use #model in the View or Partial View
#model IEnumerable<FinalProject.ViewModels.WorkerViewCardModelcs>
#foreach (var item in Model)
{
What ever logic you wish
}
I am new to MVC frame work. And i am making one page where we can see details of department by clicking on details link button.
While User click link button it fetch the all the records of the particular department in List Collection and redirect to Details View.Data has been fetched in List but while going to Details view it Generates following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DocPageSys.Models.Interfaces.DepartmentInfo]', but this dictionary requires a model item of type 'DocPageSys.Models.Interfaces.DepartmentInfo`'.
I understood the error but confusion to solve it.And stuck with this problem...
Since your Details view is strongly typed to DepartmentInfo:
#model DocPageSys.Models.Interfaces.DepartmentInfo
you need to pass a single instance of it from the controller action instead of a list:
public ActionResult Details(int id)
{
DepartmentInfo depInfo = db.Departments.FirstOrDefault(x => x.Id == id);
return View(depInfo);
}
So make sure that when you are calling the return View() method from your controller action you are passing a single DepartmentInfo instance that you have fetched from your data store.
To make it run fine initially you could simply hardcode some value in it:
public ActionResult Details(int id)
{
var depInfo = new DepartmentInfo
{
Id = 1,
Name = "Sales",
Manager = "John Smith"
}
return View(depInfo);
}
Oh, and you will notice that I didn't use any ViewData/ViewBag. You don't need it. Due to their weakly typed nature it makes things look really ugly. I would recommend you to always use view models.
Passing a list instead of a single item
This error tells you, that you're passing a list to your view but should be passing a single entity object instance.
If you did fetch a single item but is in a list you can easily just do:
return View(result[0]);
or a more robust code:
if (result != null && result.Count == 1)
{
return View(result[0]);
}
return RedirectToAction("Error", "Home");
This error will typically occur when there is a mismatch between the data that the controller action passes to the view and the type of data the view is expecting.
In this instance it looks as if you're passing a list of DepartmentInfo items when your view is expecting a single item.