Displaying Images = Int Result - asp.net-mvc

I am working with MVC5 and I am trying to display 1 image per number in an int, for example:
If the rating is 5, show 5 stars.
I have found a way to do this but it's a real horrible work around, I would prefer to understand how to right the foreach loop on this.
CODE:
public class RestaurantReview
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int Rating { get; set; }
}
=========================================================
public ActionResult Index()
{
var model =
from r in _reviews
orderby r.Name descending
select r;
return View(model);
}
=========================================================
Example of Data Source:
static List<OdeToFood.Models.RestaurantReview> _reviews = new List<RestaurantReview>
{
new RestaurantReview {
Id = 1,
Name = "Cinnamon Club",
City = "London",
Country = "UK",
Rating = 10,
},

you do this with CSS really, for example. you html may look like this:
foreach(var item in model.items){
<span id="star#(item.rating)"> </span>
<span>#mitem.name</span>
}
I dont agree with this hard coded solution, but you could do this:
var model =
from r in _reviews
orderby r.Name descending
select new { name = r.name, image = "star" + r.rating, field3 = r.blah, field4 = r.blahblah }
However as explained below, you change the image, you have to change the code, if you change the image location, you also have to change your code. If you want to change the ratings. You have to change our code.
another solution is client side: http://wbotelhos.com/raty
or something similar. https://www.google.co.uk/search?q=jquery+ratings&oq=jquery+ratings&aqs=chrome..69i57j0l5.3043j0j7&sourceid=chrome&espv=210&es_sm=122&ie=UTF-8

A simple for loop would do this:
for (i=0; i < item.Rating; i++) {
<img src="star">
}

Related

create view in mvc base tow table

This is my controller:
public ActionResult product_list()
{
using(myDatabaseEntities1 d=new myDatabaseEntities1())
{
var a = (from g in d.departments
from p in d.Tables
where p.userid == g.kod_achrai
select new { department_name = g.department_name, oved_achrai = p.fullname, teur = g.teur });
return View(a);
}
}
The select statement base on 2 tables,
I want to show this in view.
I create a view but i dont know what to put in title
exp: #model MvcApplication4.department
I attach picture of option:
Can someone help me :)
Thank in advance.
I think you want to do scaffolding , so You have to create a model class for it. like
public class deptModel
{
public string department_name { get; set; }
public string oved_achrai { get; set; }
public string teur { get; set; }
}
and in your code write this
public ActionResult product_list()
{
using(myDatabaseEntities1 d=new myDatabaseEntities1())
{
var a = (from g in d.departments
from p in d.Tables
where p.userid == g.kod_achrai
select new deptModel { department_name = g.department_name, oved_achrai = p.fullname, teur = g.teur });
return View(a);
}
}
And thin in this model class list you will find deptModel ,to use/select.
and for using two tables yo can use join if you want like this.
var a = (from g in d.departments
join p in d.Tables
on p.userid equals g.kod_achrai
select new deptModel{ department_name = g.department_name, oved_achrai = p.fullname, teur = g.teur });
and whatever you meant by title exp will be #model MvcApplication4.deptModel
you can use scaffolding template like this in your solution
hope it will help you

How do I loop through an array and add each value to my model variable? MVC Razor

I am trying to make a variable in my model that retrieves all available skills to later display them in a DDL. I have one variable that contains all of the skills and one variable that displays all of the skills an employee has already rated. I want to check all of the skills against the rated skills so that only the unrated skills are added to the new variable in the model. The only way I could think of to do this is to use a foreach loop to check for the values in the AllSkills variable.
model:
public IEnumerable<long> AvailableSkills { get; set; }
public IEnumerable<long> AllSkills { get; set; }
public IEnumerable <long> EmployeeRatings { get; set; }
public IEnumerable<Rating> Ratings { get; set; }
public IEnumerable<Skill> Skills { get; set; }
public long SkillId { get; set; }
Controller:
model.AllSkills = db.Skills.OrderBy(s => s.SkillName).Select(s => s.SkillId);
model.EmployeeRatings = db.Ratings.Where(r => r.EmployeeId == User.Identity.Name.Remove(0, 8)).OrderBy(s => s.SkillId).Distinct();
foreach (var skill in model.EmployeeRatings)
{
model.AvailableSkills = model.AllSkills.Where(s => s != skill);
}
I want to do something like the following code in the foreach loop:
model.AvailableSkills += model.AllSkills.Where(s=> s != skill); but this is not allowed.
The problem is that this for each loop above is assigning the model.AvailableSkills to the every skill but the last one that is in the foreach loop (as it should). How do I make it so that every one of the duplicate skills are excluded from model.AvailableSkills?
Using LINQ is IMO more readable if you use to query syntax opposed to the method chaining syntax.
model.AllSkills =
from skill in db.Skills
orderby skill.SkillName
select skill.SkillId;
model.EmployeeRatings =
from rating in db.Ratings
let employeeId = User.Identity.Name.Remove(0, 8)
where rating.EmployeeId == employeeId
orderby rating.SkillId
select rating.SkillId
You can use the Except() extension method to remove items from the collection.
// exclude the 'owned' skils
model.AvailableSkills = model.AllSkills.Except(model.EmployeeRatings);
And you probably want to distinct the results:
model.AvailableSkills = model.AvailableSkills.Distinct();
Last but not least:
Because you select the SkillId I'm unsure why you would order the results. This does not make sense especially because you order by different properties in both lists. Furtermore you probably want to select more details to display to the user, but to know this we need more details on your model.
Assuming EmployeeRatings contains rated skills, and you want AvailableSkills to have only skills not in EmployeeRatings but are in AllSkills, I think this is what you like to do:
model.AvailableSkills = model.AllSkills
.Where(s => !model.EmployeeRatings.Contains(s));
Consider two classes like this:
public class Skill
{
public int Id { get; set; }
}
public class Employee
{
public int[] RatedSkills { get; set; }
}
var skills = new List<Skill>
{
new Skill{ Id = 1}, new Skill{Id = 2}, new Skill{ Id = 3}, new Skill { Id = 4}
};
var emp = new Employee
{
RatedSkills = new int[] { 1,2 }
};
var availableSkills = skills.Select(s => s.Id).Except(emp.RatedSkills);
Console.Read();
The rating has an Id property an an employee has an int[] to hold his/her selected ratings. From there it's easy to filter
Following your current approach, you can use AddRange with a list. Something like:
List<long> availableSkills = new List<long>();
foreach (var skill in model.EmployeeRatings)
{
availableSkills.AddRange(model.AllSkills.Where(s => s != skill));
}
model.AvailableSkills = availableSkills;
Or you can achieve this with a more compact approach, and I believe Except removes dupes:
model.AvailableSkills = model.AllSkills.Except(model.EmployeeRatings);

PagedList - a way to use not with the whole collection

I've got simple action in which I make a request to web service to get a LIST<> of articles for specific group.
Then using pagedList (and specifying the desired page and page number) of course I specify the subset of that list I want to take. The problem is : the article for specific group can be thousand for example - and getting the info for all of them from the web service takes a lot of time and even sometimes crushes (when the articles are above 1000)
Is there a way to get the articles only for the specific page and still to use pagedList because I see that unfortunately we have to call ToPagedList method for the whole collection.
public virtual ActionResult ImportShow(String id, int? menuID, string articlegroupID, string menuforHistory,int? counter,int?page,int? pageSize,string articleDescr, int? ArticleID)
{
List<WebServiceBeaMenu> standartList = ebServiceBea.GetArticle(Convert.ToInt32(menuID), articlegroupID, "", articleDescr);
IPagedList<WebServiceBeaMenu> p_ProductsShow = standartList.ToPagedList(actualpage,actualPageSize);
p_GroupMenu.ProductMenu = p_ProductsShow;
p_GroupMenu.MenuHistory = p_GetMenuHistory.ToList();
p_GroupMenu.MenuLeft = p_GetMenuLeft.ToList();
return PartialView("ImportShow", p_GroupMenu);
}
}
here is my view
#model MvcBeaWeb.GroupMenu
#for (int i = 0; i < Model.ProductMenu.Count; i++)
{
<div>
var item = Model.ProductMenu[i];
#Html.PagedListPager(Model.ProductMenu, page => Url.Action("ImportShow", new { id = Model.LanguageName, menuID = #Session["men"], articlegroupID = Session["article"], articleDescr = Session["articleDescr"], pageSize = Session["pageSize"], page }))
</div>
You should rewrite .GetArticle() Or replace it with whith somethink like .GetPagedArticle() if you have access to WebService. This methid should have all paging params. That's the only way i think.
Your .GetArticle() method should return object like this:
public class Set<T>
{
public Set()
{
Elements = new List<T>();
}
public Set(List<T> elements, int rowsAll)
{
Elements = elements;
RowsAll = rowsAll;
}
public Set(List<T> elements, int rowsOnPage, int pageSelected, int rowsAll)
{
Elements = elements;
PageSelected = pageSelected;
RowsOnPage = rowsOnPage;
RowsAll = rowsAll;
PagesAll = (rowsAll % RowsOnPage == 0) ? rowsAll / RowsOnPage : rowsAll / RowsOnPage + 1; ;
}
public int RowsOnPage { get; set; }
public List<T> Elements { get; set; }
public int? RowsAll { get; set; }
public int PageSelected { get; set; }
public int PagesAll { get; set; }
}
Where Elements should be not all elements, but only paged one.

How to create a simple left outer join in lambda expression in EF ASP.NET MVC5

I searched hours and hours for this without any luck. I'm trying to create a lambda expression to fetch data from two tables Schedule and Request. But i'm outputting a bool here. How can i do a proper left outer join to fix this?
this is the best i could come up with
ViewBag.RequestList = db.Requests
.Include(r => r.Department)
.Select(r => db.Schedules.Any(s => s.RequestId == r.RequestId));
but its a bool not a list.
Assume my table models are as follows
public class Request{
public virtual int RequestId { get; set; }
public virtual string Remarks { get; set; }
}
public class Schedule{
public virtual int ScheduleId{ get; set; }
public virtual string Name{ get; set; }
public virtual Request Request { get; set; }
}
I'm trying to see if each and every request has one or more schedules associated with it or not. so if i could attach schedule object to request and output it as a list then thats all i need.
But I want to do it using LINQ and lambda expressions and I've seen queries as below;
var leftList = (from emp in db.Requests
join d in db.Schedules
on emp.RequestId equals d.RequestId into output
from j in output.DefaultIfEmpty()
select new { RequestId = emp.RequestId,
name = emp.Department.Name,
route = emp.Route.Name });
But that's not what i want, because i have to specify every field i need in new { RequestId = emp.RequestId, name = emp.Department.Name, route = emp.Route.Name }
Thanks a lot!
just list what you want like this:
var leftList = from emp in db.Requests
join d in db.Schedules
on emp.RequestId equals d.RequestId into output
from j in output.DefaultIfEmpty()
select new
{
RequestId = emp.RequestId,
name = emp.Department.Name,
route = emp.Route.Name,
ScheduleId=j==null?0:j.ScheduleId,
SName=j==null?""j.Name,
};

ASP.net MVC - Strongly typed object to represent a Json Object that I pass to the view

I'm using jqGrid to display some data on a page. Within the controller action, we're using an anonymous object to represent the data that the jqGrid needs. My question is, is there a way we can create a strongly typed object to represent the jqGrid data that we are sending with Json()?
Main reason for this is so that we can do unit testing with the objects that are being sent to it.
Thanks!
EDIT:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GridData(FormCollection form, string alias, string location, string state)
{
int pageSize = Convert.ToInt32(form["rows"]);
int pageIndex = Convert.ToInt32(form["page"]) - 1;
var deviceList = this._device.GetList(CreateFilter(location,alias,state),this._securityCache.GetSecurityContext(),pageSize,pageIndex);
int totalResults = deviceList.TotalRecords;
int totalPages = (int)Math.Ceiling((float)totalResults / (float)pageSize);
var jsonData = new {
total = totalPages,
page = pageIndex + 1,
records = totalResults,
rows = (from device in deviceList.Data
select new {i = device.Alias,cell = new string[]{device.Alias,device.Location,device.RatePlan,device.State,device.DateCreated.ToString()}}).ToArray()
};
return Json(jsonData);
This above here works, but we can't unit test the data that is being passed into the Json() method.
var newJsonData = new JsonJQGridReturnData();
newJsonData.total = totalPages;
newJsonData.page = pageIndex + 1;
newJsonData.records = totalResults;
List<JsonJQGridRow> list = new List<JsonJQGridRow>();
foreach (var device in deviceList.Data)
{
list.Add(new JsonJQGridRow(device.Alias, new string[] { device.Alias, device.Location, device.RatePlan, device.State, device.DateCreated.ToString() }));
}
newJsonData.rows = list.ToArray();
_cookieHelper.SaveCookie("DeviceListIndex", this._securityCache.GetSecurityContext().UserID.ToString(), COOKIE_PAGE_SIZE_KEY, pageSize.ToString());
return Json(newJsonData);
}
Here is my poor attempt at trying to wrap these into strongly typed objects. Unfortunately, running this gives me a "u is undefined" in the jqGrid file. I suspect that this is because the json being passed in is not correctly formatted. Here are the classes....
[DataContract]
public class JsonJQGridReturnData
{
[DataMember]
public int total { get; set; }
[DataMember]
public int page { get; set; }
[DataMember]
public int records { get; set; }
[DataMember]
public JsonJQGridRow[] rows { get; set; }
}
[DataContract]
public class JsonJQGridRow
{
public JsonJQGridRow(string i, string[] columns)
{
this.i = i;
this.cells = columns;
}
[DataMember]
public string i { get; set; }
[DataMember]
public string[] cells { get; set; }
}
If I understand your question you can use Generics to do this:
Model:
// represents one row in the JQGrid
class Customer
{
public string firstname { get; set; }
public string lastname { get; set; }
}
JQGrid class:
class JQGridData<TModel>
{
// add in whatever other properties you want for JQGrid
public int responseTime {get; set; };
public List<TModel> rows = new List<TModel>();
}
Controller Action :
public JsonResult GridData(int page)
{
var gridData = new JQGridData<Customer>();
// Populate your data here, this is just an example:
gridData.rows.Add(new Customer()
{
firstname = "fred", lastname = "pharkas"
});
// return the result
return Json(gridData, JsonRequestBehavior.AllowGet);
}
Result:
{
responseTime: 0
rows: [
{
firstname: "fred"
lastname: "pharkas"
}
]
}
Is that what you were asking?
David,
Here's the kinda thing i use in an app i'm working on at the moment for this type of thing. I know it doesn't provide a strongly typed object as such, but the 'list' could be a part of the model that is then sent ToArray() at the end of the piece.
public JsonResult GridData(int id)
{
// get our messages based on id
var bookingmessagesList = _repository.Find(x => x.ID == id);
var list = new ArrayList();
foreach (var bookingmessage in bookingmessagesList) //populate data containers with read data
{
list.Add(new
{
bookingmessage.ClassRowVersionDate,
bookingmessage.ID,
bookingmessage.BookingID,
bookingmessage.AssignedFrom,
bookingmessage.AssignedTo,
bookingmessage.AssignedDate,
bookingmessage.CompletedDate,
bookingmessage.MessageType,
bookingmessage.Notes
});
}
int totalOjectCount = list.Count;
return Json(new { dataitems = list.ToArray(), totalItems = totalOjectCount });
}
hope it gives you some ideas.. Will be interested to see the suggestions made.
Here's a quick take on a strongly-typed JQGridResult.
public class JQGridResult<T> : JsonResult where T : class
{
public T Model
{
get { return (T)this.Data; }
set { this.Data = value; }
}
}
Used as...
return new JQGridResult<JsonModel> {
Model = new GridModel { ... initialize model here ... }
});
where GridModel is basically a container class holding the strongly typed properties for the grid.
I feel really silly. I had a misspelling in the GridRow that was causing jqGrid to blow up. After I fixed that, I was able to get the jqGrid to work with my strongly typed object...
Now in my unit tests, I can just do...
var result = controllerToTest.GridData(form, null, null, null) as JsonResult;
var data = result.Data as JsonJQGridReturnData;
and now I can access the fields :D

Resources