I am not sure this is an error in my code or maybe something else messing with it however I have a function were I am creating a simple list from a MVC model in an ActionResult I have others that use OrderByDescending and work but this is throwing an error for some reason.
[Authorize(Roles = "Administrator, Manager, User")]
[SessionExpire]
public ActionResult PrepareShipment(int id,string sortOrder)
{
//ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
//ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
Order orderResult = (from o in db.Orders.Include("OrderItems").Include("OrderItems.Item")
where o.OrderID == id
select o).First();
orderResult = orderResult.OrderByDescending(o => o.Item.ItemName);
return View(orderResult);
}
That is my complete ActionResult the database has a table Order with another object called Item that object has a column called ItemName. I already have a view with a list in it done exclusively in the view but now I have to order that data by the item name. This is so every time an action is done on the page the list stays in the same order as when it first loaded. Right now every time I reload the page the list reorders.
Ok so I solved this in the foreach which I realize now I should have included in the original post
the orginal for each was this
#foreach (OrderItem item in Model.OrderItems) {
I fixed it by doing this to the foreach
#foreach (OrderItem item in Model.OrderItems.OrderBy(m => m.OrderItemID)) {
I never even knew you could add additional information like that to a foreach in c#
Thank you everyone for you patience with me :D
Related
I want to preface this by saying I am new to working with models. Please forgive me if this question has a simple answer.
I have been struggling to revert a listed view model back to view model. To give some background, I have a search form being passed to a model coming from my ActionResult and am then getting a filter out the results.
[ Controller ]
public ActionResult GetFilters(MembershipVM model)
{
var uDataList = new List<MembershipVM>();
model = _service.GetFilters(model);
return View("SendEmail", model);
}
[ Service ]
public List<MembershipVM> GetFilters(MembershipVM model)
{
var query = _context.Members.Where(f => f.Deleted == 0).AsQueryable();
var members = _context.Members.ToList();
query = query.Where(f => agencyTypes.Contains(f.AgencyType));
var uDataList = new List<MembershipVM>();
foreach (var member in members)
{
var uData = new MembershipVM();
uData.Email = member.Email;
uData.AgencyType = member.AgencyType;
...
uDataList.Add(uData);
}
return uDataList;
}
How can I cast the List from "_service.GetFilters" to MembershipVM? Is there a better/easier way to get the results as an object from the "_service.GetFilters" service?
Thanks so much in advance!
Daisy
I am not sure what you are trying to do here. First you get the results of your filter from this code:
model = _service.GetFilters(model);
And the definition of your method is this:
public List<MembershipVM> GetFilters(MembershipVM model)
So you would expect that this is a list of results. In short, a collection of results.
Now if you want to pass it on your ActionResult as one entity only, then getting one of your results will do the trick:
return View("SendEmail", model.Take(1).SingleOrDefault());
But why do you need to pass one entity only? But that should work with your current requirement.
As the title says. I have a page with a Job that have an ID. This ID I am storing in a Session and when I am trying to access the Company profile I just test if the Session Variable with Job ID from the tables Jobs and then I am trying to select the User ID and then with this User ID I search in UserManager and try to populate the page with some data.
Code For Company Profile:
public async Task<ActionResult> Details(string id)
{
String JobValID = Convert.ToString(Session["DetailsURL"]);
var UserJobID = context.Jobs.Where(x => x.ID.ToString() == JobValID).OrderByDescending(x => x.UserID).Select(x => x).ToString();
UserJobID = id; //This line is to see what value I got from LINQ and is still the Session value.
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await UserManager.FindByIdAsync(id);
return View(user);
}
View For this Controller is default scaffolded View from controller.
And like This I get Session["DetailsURL"]
var currentID = Url.RequestContext.RouteData.Values["id"];
Session["DetailsURL"] = currentID;
I guess this is not the standard way to get a User Profile page. But I am using an ActionLink from Job Page to get into the Company Profile.
Here ActionLink to get from JobPage to Company Profile:
#Html.ActionLink("About this company", "Details", "UserAdmin", new { id = Session["UserJobID"] }, null)
My problem is in LINQ statement, when I am trying to select UserID, it doesn't get the right value, and when I am searching in UserManager the value is still the session Value.
Found the solution here
So how I did it:
var UserJobId = (from c in context.Jobs
where c.ID == JobValID
select new { c.UserID }).Single();
var myVal = UserJobId.UserID;
id = myVal;
It has been awhile since I have used C#, but your LINQ statement seems to be getting a list of Job objects and doing ToString on the list. If Job has reference to the UserId associated with it, then the following LINQ statement should work:
var userId = context.Jobs
.SingleOrDefault(x => x.ID.ToString() == jobId)
.?Select(j => j.<accessorToUserId>) // Not sure what your schema is
.?ToString()
Notice the ?. This is just in case SingleOrDefault returns null then the following method calls won't happen. If, for some reason, more than one Job uses that jobId, which is really bad practice, replace SingleOrDefault with FirstOrDefault.
Also, Select is supposed to be used to map from type T to type U. Doing Select(x => x) is pointless since you are simply doing T -> T.
I am having an issue in my project and wonder if some can pinpoint me to where i may have gone wrong. so basically in my project i have got an ActionResult method like so:
public ActionResult PartNumberManufacturer(string id)
{
var partNumber = _Context.PartNumberTable.FirstOrDefault(x => x.partNumberId == id);
return PartialView("PartNumberView", partNumber);
}
Then this is my view
#if (Model != null && !string.IsNullOrEmpty(Model.PartNumberManufacturer))
{
#if (Model.PartNumberManufacturer == "Fr")
{
<div>
<p> This product is developed in france </p>
#if (#Model.PartNumberManufacturer == "Ger")
{
<p> This Product is developed in Germany </p>
}
well the above code works fine. but the thing is that if you look back into my ActionResult controller method , i am using :
var partNumber = Context.PartNumberTable.FirstOrDefault(x => x.partNumberId == id);
FirstOrDefault of-course will only return the first found part number in the database.
This isnot what i am looking for i don't want it only to return the first found record , i want it to return all the records that match by the search query in the database. So in order to do and after a few research online i found that i had to return the results into a list and this made me amend my ActionResult method to like this:
public ActionResult PartNumberManufacturer(string id)
{
var _methodOfRepair = Context.PartNumberTable.Where(x => x.PartNumberId == id); // changed thisline
return PartialView("PartNumberView", partNumber);
}
so yeah i get the error message saying that:
{"'System.Data.Entity.Infrastructure.DbQuery' does not contain a
definition for 'PartNumberManufacturer'"}
i made those changes. what am i doing wrong here? or is there a different approach i can be recommended to in order to achieve this?
thank you for your time.
First recommendation, read about implementing the repository pattern.
Second, if you are sending a collection of objects to your View then your View need to be expecting that data type. Change the Model data type that your View is expecting.
Inside your View, you should iterate over every element and render it.
Before I had this:
public ActionResult ShowSong(int id)
{
return view(db.PublishedSongs.Where(x => x.Id == id).FirstOrDefault());
}
and in my view:
#model MusicSite.Models.PublishedSong
<h2>#Model.SongName</h2>
#Html.ImageFor(x => x.CoverImageBytes, #Model.SongName + " Image", new { #class = "big-cover-image" })
This worked fine for just retrieving one item from DB and showing on view.
However now, I need to also pass a list to my view, because I want to show all of the items in model and just the select item that was passed through action method, how do I do this?
If I pass return View(db.PublishedSongs); to view then I no longer know which id to get to show just that one item.
As I am not that much good in .NET MVC but I will try to answer according to spring MVC knowledge.
The rough idea is to pass list to view as you are mentioned and along with it pass the id that you want to select using ViewBag. Now in view iterate over the list, while iteration check whether id come from iteration is equal to id that you passed in ViewBag.
So in controller :
public ActionResult ShowSong(int id)
{
ViewBag.SelectId = id;
return view(db.PublishedSongs);
}
In View :
(Loop over the db.PublishedSongs)
{
if(PublishedSong.id=#ViewBag.SelectId)
{
//select current PublishedSong
}
else
{
//otherwise
}
}
I have created Linq-to-SQL for a view of SQL Server, now I'm trying to display record on view, it's done :) but
problem is that it shows each name 26 times, why?
How to put it in gridview kinda thing in MVC?
Controller:
namespace EmployeeAttendance_app.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Employee Attendance";
var DataContext = new EmployeeAtdDataContext();
var EmployeeAtd = from emp in DataContext.EmployeeAtds
select emp;
return View(EmployeeAtd);
}
}
View:
<ul>
#foreach (EmployeeAttendance_app.Models.EmployeeAtd emp in (IEnumerable<Object>)ViewData.Model)
{
<li>#emp.EmplName</li>
}
</ul>
Model contains Linq-to-SQL class named EmployeesAtd.
View has been created via this query:
SELECT
dbo.HrEmployee.EmplID, dbo.HrEmployee.EmplName, dbo.AtdRecord.RecDate,
dbo.AtdRecord.RecTime, dbo.HrDept.DeptName
FROM
dbo.HrDept
RIGHT OUTER JOIN
dbo.HrEmployee ON dbo.HrDept.DeptID = dbo.HrEmployee.DeptID
LEFT OUTER JOIN
dbo.AtdRecord ON dbo.HrEmployee.EmplID = dbo.AtdRecord.EmplID
Other than cleaning up the things Adriano pointed out, I don't see anything wrong with that. You said EmployeeAtds is a SQL View, right? I would guess you have some sort of join in there that is duplicating rows.
Try to move boxing before loop:
var emps = (IEnumerable< Object >)ViewData.Model;
#foreach(EmployeeAttendance_app.Models.EmployeeAtd emp in emps)
To show data in GridView you have to use some javascript lib.
grid controls for ASP.NET MVC?