How display the last n of records in MVC - asp.net-mvc-4

i am taking last 4 four comments and want to display in the tooltip,
I am doing the below code but its showing the contents like "System.Collection.Generic.List"
var list = db.PO_Prd_Comments.Where(t => t.PO_TrgCal_ID == item.ID && t.Reply == false).OrderByDescending(t => t.PO_TrgCal_ID).Take(4).ToList();
List<string> comments = new List<string>();
if (list.Count != 0)
{
foreach (var ts in list)
{
comments.Add(ts.PrdComment);
if (list.Count == 1)
{
notify = list.SingleOrDefault().notify;
}
else
{
notify = true;
}
}
}
<td>
<a href="#" onclick="popup4(#CountID)" title="#comments"
<img src="~/Images/comment.GIF"/></a>
</td>
How i display these four comments in the tooltip.

comments is a list of string. You need to convert that to a single string and use that as the title property value.
<a href="#" onclick="popup4(#CountID)" title="#String.Join(Environment.NewLine,comments)">
<img src="~/Images/comment.GIF"/>
</a>

Related

how to Optimize multiple searches in the table

I want to select a few fields from the table and search For example, a user records the project name, color project status, project date, and so on
For example, in the search form, I want to select the project name and color of the project status and project date, and fetch the information
But the problem is that I have to apply too many (if)
How can I select and search multiple fields with the least if ?
Please see the image and the codes and help.
if (hesabrsee.Projectid != 0 && red != 0 && yealoo != 0)
{
fraindList = fraindList.Where(p => p.Projectid == hesabrsee.Projectid && p.ControlState == red && p.ControlState == yealoo);
ViewBag.yealoo = "checked";
ViewBag.red = "checked";
return View(fraindList.ToList());
}
<div class="col-md-4 col-xs-12">
<label>نام پروژه</label>
<select class="form-control" id="form_frame" name="Projectid">
<option value="" default="" selected="">انتخاب کنید</option>
#foreach (var item in ViewBag.proList)
{
<option value="#item.projectID">#item.projectName</option>
}
</select>
</div>
You can try to use the following code:
string s = "select * from Hesabrsee where Projectid=" + hesabrsee.Projectid;
s += red != 0 ? "ControlState==red" : "";
s += green != 0 ? "ControlState==green" : "";
var fraindList = _context.Student.FromSqlRaw(s).AsEnumerable();
if (FramDate != null)
{
fraindList = fraindList.Where(l => l.ControlDate.Date >= ConvertDateTime.ConvertShamsiToMiladi(FramDate));
}
if (ToDate != null)
{
fraindList = fraindList.Where(l => l.ControlDate.Date >= ConvertDateTime.ConvertShamsiToMiladi(ToDate));
}
return View(fraindList.ToList());

Retrieve selected checkboxes in an array into the controller

How can i retrieve the selected checkbox in the controller.
This is the main view where the user can choose a request access.
#using (Html.BeginForm("addBatch_CARF", "CARF", FormMethod.Post, new { #name = "register" }))
{
#Html.ValidationSummary(true)
<div id="formAlert" class="alert alert-danger">
<a class="close">×</a>
<strong>Warning!</strong> Make sure all fields are filled and try again.
</div>
var catName = "";
var displayCan = "";
var candidates = "";
for (int i = 0; i < Model.Count; i++)
{
if (catName != Model[i].request_category)
{
<li class="list-group-item list-group-item-success">
#Html.DisplayFor(modelItem => Model[i].request_category)
<span class="pull-right" style="margin-right:60px;">Special Instructions</span>
</li>
catName = Model[i].request_category;
displayCan = catName;
}
if (displayCan == Model[i].request_category)
{
candidates = Model[i].request_name;
<div class="checkbox_request">
#Html.CheckBoxFor(model => model[i].isSelected, new { #class = "is_selected" })
#Html.DisplayFor(model => model[i].request_name)
#if(Model[i].request_name == "Folder Access")
{
<span class="label label-danger">Pls specify all the drive path. Note: For accessing of drives outside PETC please proceed to Online CARF</span>
}
<span class="pull-right">
#Html.EditorFor(model => model[i].special_instruction)
</span>
#Html.HiddenFor(model => model[i].request_type_id)
#Html.HiddenFor(model => model[i].system_roles_id)
</div>
}
}
<li class="list-group-item list-group-item-success">
Access to:
</li>
<div id="employeeAdd">
#{Html.RenderAction("AddRequestor"); }
</div>
<p class="request_btn">
<button type="submit" class="btn btn-primary" id="addbtn">Save</button>
</p>
}
I have only rendered this view AddRequestor in selecting or adding an employee.
<table class="table table-hover">
#for (int i = 0; i < Model.Count; i++){
<tr>
<th>
#Html.CheckBox("checkbox", new { #class = "is_selected" })
#Html.DisplayFor(model => model[i].FullName)
#Html.HiddenFor(model => model[i].Emp_Badge_No)
</th>
</tr>
}
</table>
The main goal of this is all the chosen employees must have also all the chosen request access.
[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list, List<Employees_All_vw> emp, string[] checkboxes)
{
foreach (var x in emp)
{
int num = 1;
bool z = Convert.ToBoolean(num);
if (x.checkbox == z)
{
//add data into CARF table
CARF carf = new CARF();
carf.requestor = x.Emp_Badge_No;
carf.carf_type = "BATCH CARF";
carf.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
carf.created_date = System.DateTime.Now;
carf.active_flag = true;
db.CARves.Add(carf);
db.SaveChanges();
int id = carf.carf_id;
//add data into Request Access Table
foreach (var i in list)
{
int val = 1;
bool y = Convert.ToBoolean(val);
if (i.isSelected == y)
{
Request_Access ra = new Request_Access();
ra.request_access_id = 1;
ra.carf_id = id;
ra.request_type_id = i.request_type_id;
ra.special_instruction = i.special_instruction;
ra.ra_assignee = i.system_roles_id;
ra.dept_approval = null;
ra.dept_approval_date = null;
ra.dept_remarks = null;
ra.final_approval = null;
ra.final_approval_date = null;
ra.final_remarks = null;
ra.acknowledge_by = null;
ra.acknowledge_date = null;
ra.journal = null;
ra.closed_by = null;
ra.closed_date = null;
ra.verified_by = null;
ra.verified_date = null;
db.Request_Access.Add(ra);
}
}
db.SaveChanges();
}
TempData["MessageAlert"] = "Successfully created!";
return RedirectToAction("Batch_CARF");
}
}
I've got an error on this line if (x.checkbox == z)
Operator '==' cannot be applied to operands of type 'string[]' and 'bool'
Your parameter string[] checkboxes contains values that are typeof string (either "True" or "False") so you would need to use the Convert.ToBoolean() method before comparing if (x.checkbox == z). However this will not work since #Html.CheckBox("checkbox", ..) generates 2 inputs type="checkbox" with value="True" and a type="hidden" with value="False" so if its checked, both true and false post back and if its unchecked, then only false is posted. There is no way you can possibly match up which values belong to which employee.
Instead create a view model to represent the selection of employees
public class EmployeeVM
{
public string BadgeNumber { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
And then in your AddRequestor() method (assumes you have an Employees table)
public ActionResult AddRequestor()
{
List<EmployeeVM> model = db.Employees.Where(e => e.active_flag).Select(e => new EmployeeVM
{
BadgeNumber = e.Emp_Badge_No,
Name = e.FullName
}.ToList();
return PartialView(model);
}
and in the view
#model List<EmployeeVM>
#for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].BadgeNumber)
<label>
#Html.CheckboxFor(m => m[i].IsSelected)
<span>#Html.DisplayFor(m => m[i].Name)</span>
</label>
}
And finally, in the POST method
[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list, List<EmployeesVM> employees)
{
// To get the selected employees
IEnumerable<string> selectedEmployees = employees.Where(e => e.IsSelected);
foreach(EmployeesVM employee in selectedEmployees)
{
....
carf.requestor = employee.BadgeNumber;
....

How can i select items from the list

I am not able to get items in the list. All I get is an item from the span. How can I get items in the select. If I don't use span in the css selector, then the script generates an error that the element is not visible.
This is the HTML of the page:
<table>
<tbody>
<tr>
<td>
<div>
<div class="select2-container select2-container-active" id="s2id_agency" style="width: 150px;">
<a href="javascript:void(0)" onclick="return false;" class="select2-choice" tabindex="-1">
<span>01_me</span>
<abbr class="select2-search-choice-close" style="display:none;"></abbr>
<div>
<b></b>
</div>
</a>
<input class="select2-focusser select2-offscreen" type="text"></div>
<select name="agency" id="agency" style="width:150px;" class="select2-offscreen" tabindex="-1">
<option value="14814">01_me</option>
<option value="14333">A_RLAgency</option>
<option value="14771">Agency_20150111183734</option>
<option value="14254">RLAgency</option>
<option value="14065">unknown_agency</option></select>
</div>
</td>
</tr>
</tbody>
This is my script:
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
List<String> displayed = new ArrayList<String>();
List<String> sorted = new ArrayList<String>();
List<WebElement> verifyAgency = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By
.cssSelector("#s2id_agency > a.select2-choice > span")));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "
+ verifyAgency.size());
for (WebElement element : verifyAgency) {
System.out.println("" + element.getText());
displayed.add(element.getText());
sorted.add(element.getText());
}
Collections.sort(sorted);
log.info(sorted);
if (!displayed.equals(sorted)) {
final String failedMsg = "Agency is not in alphabatical ordr.";
log.error(failedMsg, null);
boolean passed = false;
Assert.assertFalse(passed, failedMsg);
System.out.println(failedMsg);
}
} catch (Exception e) {
final String failedMsg = "Failed trying to check agency names in alphabetical order.";
log.error(failedMsg, null);
boolean passed = false;
Assert.assertFalse(passed, failedMsg);
System.out.println(failedMsg);
}
Try out with this code:
Select objSelect = new Select(dw2.findElement(By.id("agency")));
List<WebElement> lstOptions = objSelect.getOptions();
boolean sorted = false;
for (int i = 0; i < lstOptions.size() - 1; i++) {
if (lstOptions.get(i).getText()
.compareTo(lstOptions.get(i + 1).getText()) > 0) { // Checking sorting based on natural sort
sorted = false;
break;
}
sorted = true;
}
if (sorted)
System.out.println("Sorted");
else
System.out.println("Un-sorted");
You are probably trying to use visibilityOfAllElementsLocatedBy on select list options which are not visible. Infact according to your requirement you don't need them to be visible. You can alternatively use presenceOfElementLocated
and to grab the list simple SelectElement class should be enough
Note: mine is C#
IWebElement element = driver.FindElement(By.XPath("//select[#id='agency']"));
SelectElement selectList = new SelectElement(element);
IList<IWebElement> options = selectList.Options;
And, if that's a static list you can avoid all of this quirky work and simply do
IWebElement element = driver.FindElement(By.XPath("//*[#id='agency']"));
SelectElement selectList = new SelectElement(element);
var isTrue = selectList.getText().equals("01_me / A_RLAgency / Agency_20150111183734 / RLAgency / unknown_agency")
see here

The local variable assignment was printed as output on asp.net mvc

I have a script like below on my View:
#{int count = 0;}
#foreach (var item in Model)
{
<div >
<div class="col-md-4"><img src="#item.ImageLink" />
#(count = count +1 );
#if(count ==3)
{
#(count = 0);
#Html.Raw("<div class=\"clearfix visible-md\"></div>");
}
</div>
</div>
}
The problem here is : in addition to the imageLink, the output also contain the value of count when it is assigned with value (meaning that it will print some number: 1,2,3,0 - which is value of count in each loop)
How can I resolve it?
Thanks & regards,
If you use parentheses it's output will be submitted as part of the HTML. You can use curly braces for code block as below.
#{
int count = 0;
foreach (var item in Model)
{
<div>
<div class="col-md-4">
<img src="#item.ImageLink" />
#{count = count + 1;}
#if (count == 3)
{
count = 0;
#Html.Raw("<div class=\"clearfix visible-md\"></div>");
}
</div>
</div>
}
}

How do render shape of a specific ContentPart of a ContentItem from alternative razor file?

Considering we have a simple ContentType named Product which has some fields and ContentParts such CommentPart. When we create an alternative for Product (mytheme/Views/Content-Product.Detail.cshtml) then every fields and parts should be render from the alternative file. for example we can access to fields value and display theme.
But my question is that how to render default shape of the parts of the ContentType from our alternative file?
for example the Product has CommentPart and i want to call the default Display of it in a arbitrary place of view:
#using Orchard.Utility.Extensions;
#{
if (Model.Title != null)
{
Layout.Title = Model.Title;
}
Model.Classes.Add("content-item");
var contentTypeClassName = ((string)Model.ContentItem.ContentType).HtmlClassify();
Model.Classes.Add(contentTypeClassName);
var tag = Tag(Model, "article");
var Title = Model.ContentItem.TitlePart.Title;
var CreatedUtc = Model.ContentItem.CommonPart.CreatedUtc;
var Path = Model.ContentItem.AutoroutePart.Path;
var Thumb = Model.ContentItem.Product.ThumbnailImage.FileName;
var Price = Model.ContentItem.Product.Price.Value;
var CooperatorPrice = Model.ContentItem.Product.CooperatorPrice.Value;
var Discount = Model.ContentItem.Product.Discount.Value;
var Available = Model.ContentItem.Product.Available.Value ?? false;
var Special = Model.ContentItem.Product.Special.Value ?? false;
}
#tag.StartElement
<a href="#Path" >
#if (Special != null)
{
<img class="special" src="#Url.Content("Themes/RayanTechTheme/Content/Images/specialoffer.png")" />
}
#if (Thumb != null)
{
<img class="thumb" src="#Url.Content(Thumb)" />
}
<header>#Title</header>
#if (Available != null)
{
<span class="available"></span>
}
#if (Price != null && Price > 0)
{
<span class="price">#RayanTechTheme.Helpers.CurrencyHelper.GetSeperatedCurrency(Price) تومان</span>
}
#if (Price != null && Price > 0 && Discount != null && Discount > 0)
{
<span class="prev-price">#RayanTechTheme.Helpers.CurrencyHelper.GetSeperatedCurrency(Price + Discount) تومان</span>
}
#if (CooperatorPrice != null && CooperatorPrice > 0)
{
<span class="cooperatorprice">#RayanTechTheme.Helpers.CurrencyHelper.GetSeperatedCurrency(CooperatorPrice) تومان</span>
}
#if (Discount != null && Discount > 0)
{
<span class="discount">#RayanTechTheme.Helpers.CurrencyHelper.GetSeperatedCurrency(Discount) تومان</span>
}
#if (CreatedUtc != null)
{
<span class="createdutc">#RayanTechTheme.Helpers.DateHelper.GetPersianDate(CreatedUtc)</span>
}
<div class="more">
#Display.Parts_CommentForm(Model.ContentItem.CommentPart) /// >>>>> HOW DO IT???
</div>
</a>
#tag.EndElement
How do i implement the last <div> as i mentioned?
The best way to do this is by using Orchard's Placement.
Rewrite your <div> to look like:
<div class="more">
#Display(Model.Comments)
</div>
Then in your Placement.info
<Match ContentType="MyContentType">
<Match DisplayType="Detail">
<Place Parts_CommentForm="Comments:1" />
</Match>
</Match>
When your ContentItem Shape is being rendered, the Shapes for each of its parts are already built ready for display (I think, someone like Bertrand Le Roy could correct me on this if I'm wrong).
The #Display() helper is for rendering Shapes, which are created from a Part's Driver. The Placement.info tells Orchard where these Shapes should display.
See also: https://stackoverflow.com/a/19388208/1053199