I have a table containing user information with image field and storing image in binary data.
I want to show this images on my view page in a table with user information.
my code is..
Controller
public ActionResult About()
{
var data = db.dbtable.ToList();
return View(data);
}
Get Image method // reg is object of dbtable
public FileContentResult GetImage(int id)
{
reg = db.dbtable.FirstOrDefault(i => i.RegNo == id);
if (reg != null)
{
return File(reg.Photo, "image/jpeg");
}
else
{
return null;
}
}
on view page..
#model IEnumerable<MvcMySchool.dbtable>
<table width="50">
<tr>
<th>
Registration No.
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
City
</th>
<th>
Photo
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.RegNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#*HttpContext.Current.Response.Write("<img width="75" height="75" src=#(Url.Action("GetImage", "Home", new { id = item.RegNo })) />")*#
<img width="75" height="75" src=#(Url.Action("GetImage", "Home", new { id = item.RegNo })) />
</td>
</tr>
}
</table>
It only shows the image in the first row and nothing after that.
Thanks..
May make more sense just to keep the path the image.
If you filesteam,
public FileStreamResult GetImage(int id)
{
reg = db.dbtable.FirstOrDefault(i => i.RegNo == id);
if (reg != null)
{
MemoryStream ms = new MemoryStream(reg.Photo);
return File(ms, "image/png");
}
else
{
return null;
}
}
more logical way to keep, ony way
public FileResult GetImage(int id)
{
reg = db.dbtable.FirstOrDefault(i => i.RegNo == id);
if (reg != null)
{
FileInfo fi = new FileInfo(Server.MapPath(reg.Photo));
return File(fi.OpenRead, "image/png");
}
}
for both
<tr>
<td>
<img src="/Home/GetImage/#item.RegNo" alt="" />
</td>
</tr>
Related
I am getting an exception when i trying to display the values of viewbag. I have joined two tables and stored that data in viewbag using Linq.
This is my controller action method
public ActionResult HRSeparationDetails()
{
//List<trnEsSeparationDetail> separationlist = (from list in db.trnEsSeparationDetails
// select list).ToList();
ViewBag.SeparationList = (from list in db.trnEsSeparationDetails
join R in db.mstEsEmpReasonForSeparations
on list.ReasonForSeperationId equals R.intSeperationId
select new
{
intEmployeeId = list.intEmpId,
ReasonForSeparation = R.txtReasonForSeperation,
ResiganationDate = list.dtResignationDate,
RelievingDate = list.dtRequestedRelievingDate,
SeparationRemarks = list.txtRemark
}).ToList();
return View();
}
This is my viewpage
#model IEnumerable<EMPApp.Models.trnEsSeparationDetail>
#{
ViewBag.Title = "HRSeparationDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>HRSeparationDetails</h2>
<div>
#if (ViewBag.SeparationList == null)
{
<div style="color:green"><h3>#ViewBag.SeparationerrorMessage</h3></div>
}
else
{
<table class="grid" cellpadding="0" cellspacing="0">
<tr>
<th>
<b>Employee Id</b>
</th>
#*<th>
<b>ReasonForSeparationId</b>
</th>*#
<th>
<b>Reason For Separation</b>
</th>
<th>
<b>Resignation Date</b>
</th>
<th>
<b>Relieving Date</b>
</th>
<th>
<b>Separation Remarks</b>
</th>
</tr>
#foreach (var item in ViewBag.SeparationList)
{
<tr>
<td>
#item.intEmployeeId
#*#{
Session["SeparationEmpId"] = item.intEmpId;
}
#Html.ActionLink(Session["SeparationEmpId"].ToString(), "EmployeeDashboard", "HRAdmin", new { id = #item.intEmpId }, null)*#
</td>
#*<td>
#item.ReasonForSeperationId
</td>*#
<td>
#item.ReasonForSeparation
</td>
<td>
#item.ResiganationDate
</td>
<td>
#item.RelievingDate
</td>
<td>
#item.SeparationRemarks
</td>
</tr>
}
</table>
}
Any help will be appreciated. Thanks..
ViewBag is a dynamic object and your setting the property to a collection of anonymous objects. In you foreach loop
#foreach (var item in ViewBag.SeparationList)
item is typeof object and object does not have a property intEmployeeId (or any of the other properties your define in the anonymous object). One way to handle this is to create a view model with the properties you want to display
public class SeparationDetailVM
{
public int intEmployeeId { get; set; }
public DateTime ResiganationDate { get; set; }
....
}
and in the controller
var details = (from list in ....
select new SeparationDetailVM
{
intEmployeeId = list.intEmpId,
ResiganationDate = list.dtResignationDate,
....
}).AsEnumerable();
return View(details); // no need for ViewBag
and in the view
#model IEnumerable<YourAssembly.SeparationDetailVM>
....
#foreach (var item in Model)
{
....
<td>#item.intEmployeeId</td>
<td>#item.ResiganationDate</td>
....
}
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.
Hi guys I'm currently doing a Blog Archive for my blog. I was able to call the list of blog by Year and Month but my problem is that my Month is displayed in integer. This image will show it
I created a ArchiveRepository
public IQueryable<ArchiveListModel> AchiveList()
{
var ac = from Post in db.Posts
group Post by new { Post.DateTime.Year, Post.DateTime.Month }
into dategroup
select new ArchiveListModel()
{
AchiveYear = dategroup.Key.Year,
AchiveMonth = dategroup.Key.Month,
PostCount = dategroup.Count()
};
return ac;
}
I called it in my Controller
public ActionResult Archive()
{
var archivelst = repository.AchiveList().ToList();
return View(archivelst);
}
then show it in my View
<h2>Archives</h2>
<table>
<tr>
<th>
AchiveYear
</th>
<th>
AchiveMonth
</th>
<th>
PostCount
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.AchiveYear
</td>
<td>
#item.AchiveMonth
</td>
<td>
#item.PostCount
</td>
</tr>
}
</table>
How will I convert it to integer? T_T
EDIT:
I tried googling and found this answer
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
But I don't know where to put it.. :(
Try it(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);) in View page
#foreach (var item in Model) {
<tr>
<td>
#item.AchiveYear
</td>
<td>
#System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.AchiveMonth)
</td>
<td>
#item.PostCount
</td>
</tr>
}
Try this...
AchiveMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateGroup.Key.Month),
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 am passing a viewmodel into a view containing a foreach loop. This viewmodel contains two lists. These lists are filled using Linq.
With the following code, I get the following error: The model item passed into the dictionary is of type '_320.Models.MyViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[_320.Models.MyViewModel]'.
I want to reach properties contained in the two lists in the ViewModel in my view's foreach loop.
UPDATE
I have been able to display the view by modifying the end of my controller code to:
List<MyViewModel> MyList = new List<MyViewModel>();
MyList.Add(_myViewModel);
return View(MyList);
However, it is an empty view with nothing but headers. When I attempt to change my fields in my view from something like #Html.DisplayFor(modelItem => item.rx.Rx_ID) to #Html.DisplayFor (modelItem => item.Rxes.rx.Rx_ID) it is labeled red. Is it impossible to access a property located that far down in a list?
END OF UPDATE
Model
public class MyViewModel
{
public Patient patient { get; set; }
public Rx rx { get; set; }
public Fill fill { get; set; }
public List<Rx> Rxes { get; set; }
public List<Fill> Fills { get; set; }
Controller
public ActionResult AllFilled()
{
MyViewModel _myViewModel = new MyViewModel();
List<Fill> FillList = db.Fills.Where(p => p.Status == "Filled").ToList();
List<Rx> RxList = new List<Rx>();
Rx myRx = new Rx();
foreach (var item in FillList)
{
myRx = db.Rxes.Single(p => p.Rx_ID == item.Rx_ID);
RxList.Add(myRx);
}
_myViewModel.Fills = FillList;
_myViewModel.Rxes = RxList;
return View(_myViewModel);
}
}
View
#model IEnumerable<_320.Models.MyViewModel>
#{
ViewBag.Title = "AllFilled";
}
<h2>AllFilled</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
NDC
</th>
<th>
Rx_ID
</th>
<th>
Fill_ID
</th>
<th>
Status
</th>
<th>
Filled Date
</th>
<th>
Filled By
</th>
<th></th>
</tr>
{
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.rx.NDC)
</td>
<td>
#Html.DisplayFor(modelItem => item.rx.Rx_ID)
</td>
<td>
#Html.DisplayFor(modelItem =>item.fill.Fill_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.fill.Status)
</td>
<td>
#Html.DisplayFor(modelItem => item.fill.Filled_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.fill.Filled_By)
</td>
<td>
#Html.ActionLink("Details", "Details", new { id=item.rx.Rx_ID })
</td>
</tr>
}
</table>
Your view is expecting a model of type IEnumerable<_320.Models.MyViewModel> due to the first line in the view.
#model IEnumerable<_320.Models.MyViewModel>
If you want to use a model object of type MyViewModel (as coded in your controller), change this line to
#model _320.Models.MyViewModel