pass model to view using viewbag - asp.net-mvc

i want to send two model in my view
and in other page maybe and need more
controller
ViewBag.Users = db.Users.ToList();
and in View
#using Documentation.Models
#{
var Users = (Documentation.Models.User)ViewBag.Users;
}
<table>
#foreach (var item in Users) {
<tr>
<td>
#Html.DisplayFor(item.username)
</td>
</tr>
}
</table>
but i get no answer , i know my code is not right
i got this error
foreach statement cannot operate on variables of type 'Documentation.Models.User' because 'Documentation.Models.User' does not contain a public definition for 'GetEnumerator'

you should cast viewbag.model to List of User. Not to User.
#{
var Users = (List<User>)ViewBag.Users;
}

Related

How can I read list from controller into foreach view in Mvc?

I got this error
The model item passed into the dictionary is of type 'System.Collections.Generic.List'1[CandidateScreening.Data.Entities.Patient]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable'1[CandidateScreening.Models.Patient]'.)
public ActionResult Index()
{
var Patient = _context.Patients.ToList();
return View(Patient);
}
#model IEnumerable<CandidateScreening.Models.Patient>
#{
ViewBag.Title = "index";
}
<h2>List Of the Patient</h2>
<table class="table">
<thead>
<tr>
<th>firstName</th>
<th>SurName</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td> #Html.ActionLink(item.Firstname, "Index", "detail")</td>
<td> #Html.ActionLink(item.Surname, "Index", "detail")</td>
<td> #Html.ActionLink(item.Gender, "Index", "detail")</td>
</tr>
}
</tbody>
</table>
could you tell me why I get this error?
I have try by changing IEnumerable to List but is not working yet
Assumed Patients is an Entity Framework data context, ToList() will generate list with object type set as IEnumerable<CandidateScreening.Data.Entities.Patient>, which doesn't match with object type set by #model directive (i.e. IEnumerable<CandidateScreening.Models.Patient>).
To solve this issue, simply use Select() LINQ query to project entity context into list of viewmodel class:
public ActionResult Index()
{
var Patient = _context.Patients.Select(x => new CandidateScreening.Models.Patient
{
// list of properties here
// example:
// PatientId = x.PatientId
}).ToList();
return View(Patient);
}
Or using query expression as alternative:
var Patient = (from patient in _context.Patients
select new CandidateScreening.Models.Patient
{
// list of properties here
// example:
// PatientId = patient.PatientId
}).ToList();

How to retrive data from ViewData in foreach loop

Hi I have get records in ViewData["TutorList"] = GetData.Tables[0];
Here GetData DataSet and in that table[0] is bind with ViewData["TutorList"]
#foreach (var item in (DataTable)ViewData["TutorList"])
{
<tr>
<td>#item["Name"].ToString()</td>
</tr>
}
How Can I get all the records in foreach
The following code should give you want you want
#foreach (DataRow item in ((DataTable)ViewData["TutorList"]).Rows)
{
<tr>
<td>#item["Name"].ToString()</td>
</tr>
}
But I would suggest that you use a view model specific to the view and use the associated Html helpers in your view.

View passing wrong viewmodel

I've created a website using ASP.Net MVC5 (VS 2013) but I guess the same problem would present itself in MVC3 or MVC4
I have the following view:
#model IEnumerable<WilhanWebsite.Models.TestimonialViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Testimonial.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Testimonial.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Testimonial.Timestamp)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Testimonial.TestimonialId }) |
#Html.ActionLink("Details", "Details", new { id=item.Testimonial.TestimonialId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Testimonial.TestimonialId })
</td>
</tr>
}
</table>
The Index action of my Testimonial controller sends back a List and the view displays existing testimonials correctly in the html table. My problem is that when I click the Edit hyperlink I get the following error:
The model item passed into the dictionary is of type
'WilhanWebsite.DomainClasses.Testimonial', but this dictionary
requires a model item of type
'WilhanWebsite.Models.TestimonialViewModel'
I was previously using DomainClasses.Testimonial as the model passed between controller an view but today I refactored to create the new dedicated view model. It seems strange that the view is happy to process the new viewmodel when displaying the data so why is it passing the old DomainClasses.Testimonial when I click the Edit link?
Any help greatly appreciated!
The View expects #model IEnumerable<WilhanWebsite.Models.TestimonialViewModel> so you have to return it from the Controller's Index action method. Without seeing your controller I would guess that your returning a List of type Testimonial rather than a List of Type TestimonialViewModel
// GET: /Testimonial/
public ActionResult Index()
{
List<TestimonialViewModel> testimonialViewModel = new List<TestimonialViewModel>();
// Add some testimonials to your list.
return View(testimonialViewModel);
//NOT THIS - IT WILL THROW THE ERROR YOUR GETTING
return View(db.Testimonial.ToList());
}
//Testimonial/Index
#model IEnumerable<WilhanWebsite.Models.TestimonialViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Alternativly if you are returning a System.Collection and TestimonialViewModel is specified. Make sure that its implements IEnumerable. The following types do.
ICollection
IDictionary
IDictionaryEnumerator
IEnumerable
IEnumerator
IHashCodeProvider
IList
I was able to fix by updating the Edit action to the following:
public ActionResult Edit(int id)
{
var query = from t in _context.Testimonials
where t.TestimonialId == id
select t;
TestimonialViewModel tvm = new TestimonialViewModel();
tvm.Testimonial = query.First();
return View(tvm);
}

Unable to pass the same object with different result to partial view on the Home/Index controller in mvc 3

public ActionResult Index()
{
List<pInfo> pobj = new List<pInfo>();
pobj = (from pid in db.pInfoes
orderby pid.pId descending
select pid).ToList();
return View(pobj);
}
public ActionResult toprank() ///partial view
{
List<pInfo> pobj = new List<pInfo>();
pobj = (from pid in db.pInfoes.Where(c => c.DateCreated < DateTime.Now)
orderby pid.Score descending
select pid).Take(3).ToList();
return PartialView("toprank", pobj);
}
\\\ Index.csHtml
#model IEnumerable<TestProj.pInfo>
<table>
<tr>
<td>
#foreach (var item in Model)
{
<table>
<tr>
<td>
<iframe width="560"
height="300"
src="#item.pUrl"
frameborder="0"></iframe>
</td>
</tr>
</table>
}
</td>
<td>
#{Html.RenderPartial("toprank", model);}
</td>
</tr>
</table>
I am passing different result set for same Model i.e pInfo. on partial view and Index actionresult on the Home Controller. When I am trying to render the partial view on the Index view page I am getting the same result-set from the Index action result two times one in the table and another in the #{Html.RenderPartial("toprank", model);} ... I am sure I am missing some basic understanding of how the partial view works but unable to figure it out for last 3 hrs. If I change the url to partial view i.e (home/toprank ) then I get the resultset I want but its not coming on the Home/Index page
Please let me know if my design concept is wrong.. I am starting to feel that this is probably the wrong approach to get this working..
if you want to see the toprank() called you need to use Html.Action not partial, change the view to this :
<td>
#Html.Action("toprank")
</td>

MVC 3 - The model item passed into the dictionary is of type 'System.Collections.Generic.List`1

Hi I am very new to mvc and need help
I created this
public ActionResult Index()
{
var joblist = (from s in _entities.TaleoJobs
group s by new { s.JobTitle}
into myGroup
where myGroup.Count() > 0
select new { myGroup.Key.JobTitle }
);
return View(joblist.ToList());
}
but when I create the view I get the following error
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType01[System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[careers.TaleoJobs]'.
Here is the code for the view
*#model IEnumerable<careers.TaleoJobs>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
JobTitle
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.JobTitle)
</td>
</tr>
}
</table>*
I would be grateful if anyone can help - tried looking at other examples but i am at a loss.
When you are selecting the list, you are only selecting the JobTitle, which is a string. So your list is indeed a List<string>.
You can either update your select to select the entire object:
var joblist = (from s in _entities.TaleoJobs
group s by new { s.JobTitle}
into myGroup
where myGroup.Count() > 0
select s
);
Or, keep your current select and update the type of the view to:
IEnumerable<string>

Resources