Hi guys I have this data from my table
details_ID | Author | DetailTitle | DetailDescription | DateCreated | DateUpdated
12 |admin | Test | Just a test | 12/5/2012 | 12/5/2012
13 |admin | Test2 | Dog vs cat | 12/5/2012 | 12/5/2012
14 |admin | Test3 | blah blah | 12/5/2012 | 12/5/2012
I'm calling them in my view as a list
public ViewResult Index()
{
return View(db.ProjectDetails.ToList());
}
and my view
#model IEnumerable<ProjectXYZ.Models.ProjectDetail>`
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>Author</th>
<th>DetailTitle</th>
<th>DetailDescription</th>
<th>DateCreated</th>
<th>DateUpdated</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.Author)</td>
<td>#Html.DisplayFor(modelItem => item.DetailTitle)</td>
<td>#Html.Raw(item.DetailDescription)</td>
<td>#Html.DisplayFor(modelItem => item.DateCreated)</td>
<td>#Html.DisplayFor(modelItem => item.DateUpdated)</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.details_ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.details_ID })
</td>
</tr>
}
</table>
Problem: I just want to view a single item in my view with details_ID = 12
I know I have to do some querying here on my controller but don't know how..
I appreciate any help.. :)
For an instant result you can try this:
return View(db.ProjectDetails.Where(p => p.details_ID == 12).ToList());
but you should filter it as you fetch data from the database.
You have
#Html.ActionLink("Delete", "Delete", new { id=item.details_ID }) </td> </tr> }
Out of the scope of foreach, so item is undefined
Got it to work guys. I added this query on my controller:
{
var pd =
(from ProjectDetail in db.ProjectDetails
where ProjectDetail.details_ID == 12
select ProjectDetail
)
.ToList();
return View(pd);
}
-still thanks to the people who tried to help me.. :)
Related
I have a page that displays a list of courses for an individual. The page allows a user to delete a course from the selected users course list. When the delete button is clicked, that course should be deleted from the course list and the list of courses should be re-displayed. In my controller I was trying to delete the record, then call the listCourses view (view that initially lists the courses for a user) but when I click the delete button, nothing happens. Below is my code:
View to select a student:
#foreach (var stu in Model)
{
<tr>
<td class="stulisttd">
#stu.Id
</td>
<td class="stulisttd">
#stu.fname
</td>
<td class="stulisttd">
#stu.lname
</td>
<td class="thEditButton">
#using (Ajax.BeginForm("addCourses", "ManageStudentCourses", stuEditCourses))
{
#Html.TextBox("stuId", (string)stu.Id, new { #class = "listCourseText" })
<input type="submit" id="addCourses" name="addCourses" value='Add Courses' class="AllTracksButtons" />
}
</td>
<td class="thEditButton">
#using (Ajax.BeginForm("listCourses", "ManageStudentCourses", stuEditCourses))
{
#Html.TextBox("stuId", (string)stu.Id, new { #class = "listCourseText" })
<input type="submit" value="List Courses" class="AllTracksButtons" id=#stu.Id />
}
</td>
</tr>
}
View that lists the courses for user selected:
#foreach (var course in Model)
{
using (Ajax.BeginForm("deleteCourses", "ManageStudentCourses", stuListEditCourses))
{
<tr class="trCourseList">
<td>
#course.courseAbNum
#Html.TextBox("courseAbNum", (string)course.courseAbNum, new { #class = "editCourseText" })
</td>
<td>
#course.courseDesc
</td>
<td>
#course.status
</td>
<td>
#course.grade
</td>
<td>
#course.credits
</td>
<td>
<input type="submit" value="Delete" class="courseListButtons" id="displayEdit" />
</td>
</tr>
}
deleteCourses controller:
public PartialViewResult deleteCourses(string courseAbNum)
{
KuPlanEntities db = new KuPlanEntities();
var deleteCourse = (from course in db.COURSE_TAKEN
where course.courseAbNum == courseAbNum && course.Id == "000160228"
select course);
foreach (var course in deleteCourse)
{
db.COURSE_TAKEN.Remove(course);
db.SaveChanges();
}
var stuCourses = (from studCourse in db.COURSE_TAKEN
join course in db.COURSEs on studCourse.courseAbNum equals course.courseAbNum
where studCourse.Id == "000160228"
select new courseListViewModel { id = studCourse.Id, courseAbNum = studCourse.courseAbNum, status = studCourse.status, grade = studCourse.grade, courseDesc = course.courseDesc, credits = course.credits });
return PartialView("~/Views/ManageStudentCourses/listCourses.cshtml", stuCourses);
}
I think you're going to have an issue with this code
foreach (var course in deleteCourse)
{
db.COURSE_TAKEN.Remove(course);
db.SaveChanges();
}
You'll likely get the error "Collection was modified; enumeration operation may not execute."
To get around this you can use this hack
while (db.COURSE_TAKEN.Where(x => x.ID == ID).Count() != 0)
{
COURSE_TAKEN course = db.COURSE_TAKEN.Where(x => x.ID == ID).FirstOrDefault();
db.COURSE_TAKEN.Remove(course);
db.SaveChanges();
}
Hope this helps.
I have the following Razor lines for now:
<table border=1 cellpadding=3 cellspacing=1 rules="rows" frame="box">
<tr>
<th>Türkçe Söz Dizisi</th>
<th>English Word Sequence</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tr)
</td>
<td>
#Html.DisplayFor(modelItem => item.En)
</td>
<td>
#Html.ActionLink((String)#ViewBag.Edit, "Edit", new { id=item.ID }) |
#Html.ActionLink((String)#ViewBag.Delete, "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
However, I will add some columns automatically from the program to database table. I need a way to print this th's and td's accordingly. In short, I need a way to go through Model's dynamic columns. How can I achieve this?
EDIT: My Model type here is "Proposal". However, I want to reach dynamic attribute of Proposal.Type.Word(Tr, En, or any other added Language Enum). How can I?
#foreach (var item in Model) {
Type objectType = Type.GetType(typeof(RexamOneriSistemi.Models.Word).AssemblyQualifiedName);
System.Reflection.PropertyInfo[] fields = objectType.GetProperties();
<tr>
<td>#Html.DisplayFor(modelItem => item.ID)</td>
<td>#Html.DisplayFor(modelItem => item.Owner.Name)</td>
#foreach (System.Reflection.PropertyInfo f in fields) {
if (f.Name.ToString() == #HttpContext.Current.Session["Language"].ToString())
{
<td>
// What to do here exactly to get item.Type.Word.[dynamic attribute]?
</td>
}
</tr>
}
I can get Razor String
string s = "#Html.Displayfor(modelItem => item.Type.Word." + System.Web.HttpContext.Current.Session["Language"] + ")"
Resulting: #Html.Displayfor(modelItem => item.Type.Word.Tr)
Can I insert a string to be rendered as Razor Syntax? If yes, how?
I have tried this code and it works
<table border=1 cellpadding=3 cellspacing=1 rules="rows" frame="box">
<tr>
#{
Type objectType = Type.GetType(typeof(yourProjectNamespace.Models.Language).AssemblyQualifiedName);
System.Reflection.PropertyInfo[] fields = objectType.GetProperties();
foreach (System.Reflection.PropertyInfo f in fields)
{
<th> #f.Name.ToString() </th>
}
}
</tr>
#foreach (yourModelType item in Model) {
<tr>
foreach (System.Reflection.PropertyInfo f in fields)
{
<td>#Html.Display(f.Name.ToString())</td>
}
<td>
#Html.ActionLink((String)#ViewBag.Edit, "Edit", new { id=item.ID }) |
#Html.ActionLink((String)#ViewBag.Delete, "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
To get Assemply Qualified Name of your class , see this link here
Came across this question, wrote this maybe it will help someone else. This code will dynamically load your model into a table.
#model System.Collections.Generic.List<App.Client.Models.MyModel>
<table>
<thead>
<tr>
#foreach (var property in Model.GetType().GetGenericArguments()[0].GetProperties())
{
<th>#property.Name</th>
}
</tr>
</thead>
<tbody>
#foreach (var modelItem in Model)
{
<tr>
#foreach (var property in modelItem.GetType().GetProperties())
{
<td>#property.GetValue(modelItem)</td>
}
</tr>
}
</tbody>
</table>
i've a table name Info. i want to create a partial view of this table of a strongly typed.
my partial view in View/Shared is _InfoView.cshtl like:
#model IEnumerable<RealTest.Models.ifo>
<h2>_InfoView</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
name
</th>
<th>
address
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td>
#Html.DisplayFor(modelItem => item.address)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Details", "Details", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
my View page is like:
#model IEnumerable
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
#Html.Partial("_InfoView")
now i want to call it from another strongly typed view. when i called it it seems that it didn't get required data for partial view.now how i should pass partial view data???
#{Html.RenderPartial("is _InfoView", model);}
where your model would need to be a collection of ifo objects.
You can call it like this
#Html.Partial("ProdItemColors",Model.PropertyName)
For example, If you have a ViewModel called Customer which has a Collection property of type Info like this
public class Customer
{
public string CustomerName { set;get;}
public IList<Info> InfoItems { set;get;}
public Customer()
{
InfoItems=new List<Info>();
}
}
public class Info()
{
public string Name { set;get;}
}
Now from your main view which is bounded to your Customer class, you can call it like this
#model Customer
<p>#Model.CustomerName </p>
#Html.Partial("_InfoView",Model.InfoItems)
Assuming you have a View called _InfoView.cshtml either in the ~/Views/Shared folder or ~/Views/YourcontrollerName folder.
Make sure your Partial view is bounded to Info class
#model IEnumerable<Info>
<p>do something inside this</p>
I am making an MVC3 web application.I have a table which is filled with data from my database but was wondering how i could make it show only the first three lines of my synopsis instead of all 10 lines.I think this has something to do with HTML Helpers but was wondering if any of you could help me find the right code?????
Any help would be greatful!
#model IEnumerable<TheatreGroup.Models.Show>
#{
ViewBag.Title = "Shows";
}
<h2>
Shows</h2>
<p>Below is a list of shows which will be avalible in the next couple of weeks</p>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm())
{
<p>
Find by name: #Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
<table>
<tr>
<th>
#Html.ActionLink("name", "Index", new { sortOrder = ViewBag.nameSortParm,})
</th>
<th>
#Html.ActionLink("writer", "Index", new { sortOrder = ViewBag.writerSortParm,})
</th>
<th>
#Html.ActionLink("synopsis", "Index", new { sortOrder = ViewBag.synopsisSortParm, })
</th>
<th>
</th>
</tr>
#foreach (var item in Model){
<tr>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td>
#Html.DisplayFor(modelItem => item.writer)
</td>
<td>
#Html.DisplayFor(modelItem => item.synopsis)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.showid }) |
#Html.ActionLink("Details", "Details", new { id = item.showid }) |
#Html.ActionLink("Delete", "Delete", new { id = item.showid })
</td>
</tr>
}
</table>
I'll divide my answer into two state:
You need the other 7 lines somewhere further down the flow of the page (like a 'show more results' link)
You don't need the rest of the list.
Solution 1:
Use what #Dangerous said.
#for (int i=0; i<3; i++)
{
#Html.DisplayFor(m => m[i].name) // And the rest of the data
}
please take note that if you don't have 3 elements this code will throw an exception.
what you can do is check if the count is smaller than 3 and then run to that number.
You might also like to run still on the foreach loop and just give the some sort of class that will hide it new { #class = 'hidden' } and then when you press some line, just use Javascript (jQuery) to show them.
Solution 2:
If you don't need the rest of the elements, when sending the model to the view just use take.
public ActionResult Action()
{
var model = GetListFromDatabase().Take(3); // LINQ
return View(model);
}
You might need a ToList() to make it work, it depends
that way you can keep your code as is, just shorten the number of elements sent to the View.
Hope it helps !
You are using #foreach (var item in Model) to display each line.
Try using #for (int i=0; i<3; i++) so that the loop just displays the first 3 items.
You will then need to reference the model as #Html.DisplayFor(m => m[i].name) etc for the Display For's. I believe that should work.
I am trying to display a list in a View, how to fix this error?
The model item passed into the dictionary is of type
'System.Data.Objects.ObjectQuery1[System.Linq.IGrouping2[System.Int32,mvc3Post.Models.Contact]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[mvc3Post.Models.Contact]'.
controller:
public ActionResult Index()
{
AdventureWorksEntities db = new AdventureWorksEntities();
var result = from soh in db.SalesOrderHeaders
join co in db.Contacts
on soh.ContactID equals co.ContactID
orderby co.FirstName
group co by co.ContactID into g
select g;
return View(result.AsEnumerable());
}
view:
#model IEnumerable<mvc3Post.Models.Contact>
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
NameStyle
</th>
<th>
Title
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.NameStyle)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ContactID }) |
#Html.ActionLink("Details", "Details", new { id = item.ContactID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ContactID })
</td>
</tr>
}
</table>
Updated now that I see the controller method:
You might need to transform your LINQ result set into a list or something (e.g., contacts.ToList()) more concrete.
Another alternative might be to create a root object for your page's list object to live on. I find it a little easier to follow and maintain if each View has a corresponding Model class that represents it's entire state.
I think either route will resolve your issue though. I think that the latter is probably the better way if I had to recommend one vs the other.