Show Unique values From Table in mvc - c#

I want to show unique values so that only unique link will be shown. what can i do please tell as soon as possible
[Here i want to show unique Value but here is repeatetion of values][1]
My controller is this
public ActionResult AdminStudentAttendance()
{
AdmissionDBEntities obj = new AdmissionDBEntities();
var v = obj.AddTables.ToList();
return View(v);
}
My View is this
#model IEnumerable<AMSPractice.Models.AttendanceIn>
#using AMSPractice.Models;
<h2>ShowStudentAttendance</h2>
#foreach (var a in Model)
{
#Html.ActionLink(a.RollNo,"OneStudentDates","Attendance", new { nid = a.RollNo }, null) <br />
}

Inside of your foreach, it looks like the only property of the model you care about is the RoleNo. Explore something like this:
#foreach (var roleNo in Model.Select(m => m.RoleNo).Distinct())
{
#Html.ActionLink(roleNo,"OneStudentDates","Attendance", new { nid = roleNo }, null) <br />
}
You may need to play with that a bit, but basically you are appending a filter to Model to first give you only the RoleNo properties of each, then unique only.

Use Distinct to get unique values.
var uniques= Model.Select(x => x.RollNo).Distinct().ToList();
#foreach (var a in uniques)
{
#Html.ActionLink(a,"OneStudentDates","Attendance", new { nid = a }, null) <br />
}

Related

asp.net razor: items from list in model are not displayed in dropdown

I am trying to display the items from my list inside my model in a dropdown.
I tried:
<select asp-for="Requeststatus" asp-items="#Model.ThemeLinkingType"></select>
This renders a dropdown list, but with an empty list.
However, if I try:
#{
foreach (var item in Model.ThemeLinkingType)
{
<p>#item.DisplayName</p>
}
}
I get my items from my list returned in a nice little (not dropdown) kinda list.
This is the getter:
public List<ThemeLinkingType> ThemeLinkingType
{
get
{
var result = new List<ThemeLinkingType>();
foreach(var item in Enum.GetValues(typeof(ItemType)))
{
var name = item.ToString();
var id = (int)item;
var itemToAdd = new ThemeLinkingType
{
InternalName = name,
Id = id,
DisplayName = GetDisplayName(name)
};
result.Add(itemToAdd);
}
return result;
}
}
SOmeone explain the issue to me please.
Thank you!
You need to set asp-items with a SelectList type data:
#{
var l = new SelectList(Model.ThemeLinkingType, "Id","DisplayName");
}
<select asp-for="Requeststatus" asp-items="#l"></select>

The model item passed into the dictionary is of type 'AMSPractice.Models.AddTable'

I am very new to asp.net and i am stuck on that code i cant resolve this error
"The model item passed into the dictionary is of type 'AMSPractice.Models.AddTable', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AMSPractice.Models.AddTable]'."
I want to show only one value for example in my table there is more than one values name "first" so i want to show only one time "first" so when we write
FirstOrDefault then give error and when we write Where then error is not shown
but i want back only one value where return more then one values.
Here is my code
Controller
public ActionResult Login(string Name,string TeacherID)
{
AdmissionDBEntities obj = new AdmissionDBEntities();
AddTable t = new AddTable();
var v = obj.AddTables.FirstOrDefault(a => a.Teacher.Equals(Name) && a.Teacher_Id.Equals(TeacherID));
if (v != null)
{
**var var = obj.AddTables.FirstOrDefault(b => b.Teacher==Name);**
return View(var);
}
return RedirectToAction("/Home/Index");
and my View is:
#model IEnumerable<AMSPractice.Models.AddTable>
<h3>Classes Assigned</h3>
<br /><br />
<ul>
#foreach (var a in Model)
{
<li>
#Html.ActionLink(a.Class,"Sections","Attendance", new { nid = a.Foreign_Id }, null)
</li>
}
</ul>
Your issue is from the way you have strongly typed your view. From your controller, when you return return View(var); you are passing a single object to your view, yet your view is strongly typed to expect an IEnumerable of the AddTable object.
You either need to return an IEnumerable from your controller, or change your view to expect only a single object.
Try the following to change your view to expect only a single object.
In your view change your strongly typed #model from what you have to #model AMSPractice.Models.AddTable
At that point, you wouldn't need the foreach and you would just have the following.
<li>
#Html.ActionLink(a.Class,"Sections","Attendance", new { nid = Model.Foreign_Id}, null)
</li>

Use linq to check if the contents of an array are in a column in the database

I have a function that returns a list of ids based on a separate selection. This function returns all the ids and they are displayed as checkboxes in the view. Once I select some of the checkboxes, they are saved to the database as a comma delimited string. When editing the selections, the user needs to be able to deselect selected check boxes and select alternate ones. The issue I have is how to set the checkboxes as checked that exist in comma delimited string in the database. I have a linq statement that creates an array of strings, but I'm not sure how to check any of the checkboxes that are in the array based on their ID.
Here are the functions in the ViewModel:
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.vwMapDocNamesToSecurityUsers
select new
{
t.DocName,
t.DocNameId,
t.DocTypeId
}).Distinct()
.Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public String[] GetDocNamesForDocTypeId(int? docTypeId)
{
var nameCkBoxes = DocNamesByDocTypeIdList().Where(m => m.Group.Name == docTypeId.ToString()).ToString().Split(',');
//Set the ids in the array as checked in the view?
return nameCkBoxes;
}
Foreach loop in the view:
<div class="ckDocNames">
#foreach (var dn in Model.GetDocNamesForDocTypeId(Model.DocTypeId))
{
<div class="checkboxContainer, editCkBoxes">
<input class="ckBoxes" type="checkbox" name="DocNameId" value="#dn.Value" dtid="#dn.Group.Name" />#dn.Text<br />
</div>
}
</div>
from your previous question and also from my answer there :)
you can
public IEnumerable<int> GetDocNamesForFilterId(int id)
{
using (var db = new ARXEntities())
{
var selectedIds = (from t in db.ServiceAccountFilters
where t.FilterId == id
select t.DocNameId).ToList();
return selectedIds;
}
}
and in the FilterModel add new property for the selectedIds
public IEnumerable<int> SelectedDocNames { get; set; }
and in the GET Edit Action add this
var model = new FilterViewModel
{
...
SelectedDocNames = GetDocNamesForFilterId(serviceAccountFilter.FilterId);
};
and in your view you should populate all checkboxes and just check what is choosen before like below to let the user check or uncheck any one in the edit mode
#foreach (var dn in Model.DocNamesByDocTypeIdList())
{
<div class="checkboxContainer">
<input class="ckBoxes" type="checkbox" name="selectedDocIds" checked="#Model.SelectedDocNames.Contains(int.Parse(dn.Value))" value="#dn.Value" dtid="#dn.Group.Name" />#dn.Text<br />
</div>
}
and in the POST action just check what are selected by the user as below
var selectedIds = form.GetValues("selectedDocIds");

how to use a foreach in a view page

Trying to pass a list of confirmed orders to the supplier page (checked with breakpoint the list is being past) just having problems using a foreach to display the list in the view.
//SupplierController
public ActionResult Index()
{
BuyABicycle_Entities db1 = new BuyABicycle_Entities();
IEnumerable<BicycleOrder> All_Orders = (from c in db1.BicycleOrders
where c.Id >= 1
select c).ToList();
SupplierVM model = new SupplierVM { allOrders = All_Orders };
return View(model);
}
//SupplierVM
public class SupplierVM
{
public IEnumerable<BicycleOrder> allOrders { get; set; }
}
Views/Supplier/Index
#model BicycleShop.ViewModels.SupplierVM
#{
ViewBag.Title = "Supplier";
//var orders = (IList<BicycleOrder>) Model.;
// var orders = (List<BicycleOrder>) Model.Order);
}
#using (Html.BeginForm())
{
<table>
#foreach (var _Order in Model.allOrders)
{
<text>
<tr>
<td>#_Order.CustomerName</td>
</tr>
</text>
}
</table>
<input type="submit" />
}
This throws the error with #foreach (var _Order in Model.allOrders)
Compiler Error Message: CS0012: The type 'IdeaBlade.EntityModel.Entity' is defined in an assembly that is not referenced. You must add a reference to assembly 'IdeaBlade.EntityModel, Version=6.1.7.0, Culture=neutral, PublicKeyToken=287b5094865421c0'.
Foreach loop for tables in MVC4
do I need to declare a variable for the list at the top and then run through that
any help appreciated. thanks
Your view specifies the model as an IEnumerable<SupplierVM>. So to iterate over the orders, you would first have to iterate over the suppliers:
#foreach (var supplier in Model)
{
foreach (var order in supplier.allOrders)
{
...
}
}
However, it seems you're not actually passing many SupplierVM instances, but just one. Therefore, you should change the view's model to:
#model BicycleShop.ViewModels.SupplierVM
And, then you can directly iterate over the orders:
#foreach (var order in Model.allOrders)
{
...
}
maybe razor is getting confused between HTML and code:
try this:
#foreach (var _Order in Model)
{
<text>
<tr>
<td>#Html.TextBoxFor(x => x.allOrders)</td>
<td>#_Order.allOrders</td>
#<td>#Html.TextBoxFor(x => x.CustomerName, new { #readonly = true }) </td>
#foreach(var item in _Order)
{
item.ItemProp <br />
}
</tr>
</text>
}
inside the {} razor is expecting it all the be code, if you want to put HTML in there - multi-line use <text></text> for one line use #:

How to get the selected list of items from checkboxlist and pass it to the Action in MVC4

I am trying to implement a checkboxlist in my MVC application. here I need to get the selected checkboxlist values pass it to #html.ActionLink().
I have searched many sites including Stackoverflow but there is no model binding of database values and getting the selected checkbox values and passing to an action.
Eg :https://stackoverflow.com/questions/4872192/checkboxlist-in-mvc3-0
and I tried from this link. CheckBoxList multiple selections: how to model bind back and get all selections?
How to get the selected productid from the checkbox list.
Any examples.. ??
view:
#foreach (var item in Model.Tags)
{ <label>
<input type="checkbox" name="tag" value="#item.TagID" #if (item.Selected) { <text>checked="checked"</text> } />#item.Name
</label>
}
controller:
[HttpPost]
public RedirectToRouteResult Edit(IEnumerable<Guid> tag)
{
using (var dc = new MyDataContext())
{
var existing = dc.Tag
.Select(i => i.TagID)
.ToList();
// remove old
foreach (var id in existing.Except(tags.EmptyIfNull()))
dc.Tag.DeleteOnSubmit(dc.Tag.Single(k => k.TagID == id);
// add new
foreach (var id in tags.EmptyIfNull().Except(existing))
dc.Tag.InsertOnSubmit(new Tag() { TagID = id, });
dc.SubmitChanges();
}
return RedirectToAction("List");
}

Categories