Passing Field Name to Razor #helper in Webmatrix pages C# - c#

This code obtains a listing of unique org names for display within my .cshtml page:
IEnumerable<dynamic> data = db.Query("Select * from provider
where submitter_element = '210300'");
//the 210300 could be any value passed to the query
var items = data.Select(i => new { i.org_name }).Distinct();
foreach(var name in items){
<text>#name.org_name<br></text>
The records in data are each unique themselves, but the data in each field contains the same values i.e. multiple providers have the same org_name.
I want to be able to reuse the data multiple times to create multiple unique lists. I was hoping to pass this to a #helper for display. To that end, I have the following:
#helper ListBoxDistinctDisplay(IEnumerable<dynamic> queryResult)
{
IEnumerable<dynamic> distinctItems = queryResult.Select(i => new { i.org_name }).Distinct();
foreach(var listItem in distinctItems){
<text>#listItem.org_name<br></text>
}
Then in my .cshtml page I do this:
#DisplayHelpers.ListBoxDistinctDisplay(data)
...and BINGO, I get my unique list on my "view" page.
The works perfectly, except as you see I am having to indicate .org_name within the helper.
My question is how can I pass the field name (org_name) into the helper so that my helper can be re-used no matter he field name?
OR...is there a totally different approach all together that I am unaware of?
THANKS!

Since you like to use dynamic, I'll stick with that.
You may want to pass selector:
#helper ListBoxDistinctDisplay(IEnumerable<dynamic> queryResult, Func<dynamic, dynamic> selector)
{
IEnumerable<dynamic> distinctItems = queryResult.Select(x => new {selectedField = selector(x)}).Distinct();
foreach (var listItem in distinctItems)
{
<text>#listItem.selectedField<br/></text>
}
}
Call it:
#DisplayHelpers.ListBoxDistinctDisplay(data, x => x.org_name)

Related

Putting data from two tabels in one ViewData

I'm trying to put data form two tabels (AcademicDegrees, Lecturers) conneted by one to many relation into one ViewData to generate options to field (with label and id as value). It shoud be somthing like this where id are used as values nad other field as label.
ViewData["ClassroomsId"] = new SelectList(_context.Classroom, "ClassroomsID", "Number");
When all the date for field was in one table I used getter form field to get it.
[NotMapped]
public string toStringVar => FirstName + " " + LastName;
When I added tabel with academic degrees I moved to different solution.
var lecturers = _context.Lecturer;
var degree = _context.AcademicDegrees;
var lecturersList = new List<SelectListItem>();
foreach (Lecturers l in lecturers)
{
_context.AcademicDegrees.Where(d => d.AcademicDegreeId == l.AcademicDegreesId).Load();
foreach(AcademicDegrees d in degree)
{
lecturersList.Add(new SelectListItem(
$"{d.Name} {l.FirstName} {l.LastName}", l.LecturersID.ToString()
));
}
}
ViewData["LecturersId"] = new SelectList(lecturersList);
The problem is that it isn't interpreted as I want it to be.
I also can't put it directly in to SelectList because it doesn't have empty constructor or add method. Is there any other way to implement a SelectList?
In my opinion, it is like redundant work as you have the IEnumerable<SelectListItem> instance which can be used to build the select option.
And you pass IEnumerable<SelectListItem> instance to create the SelectList instance.
Would suggest to pass IEnumerable<SelectListItem> value to ViewData.
Solution for IEnumerable<SelectListItem>
Controller
ViewData["LecturersId"] = lecturersList;
View
#Html.DropDownListFor(model => model./*YourProperty*/, (IEnumerable<SelectListItem>)ViewData["LecturersId"])
Updated
Since you are using ASP.NET Core MVC, with tag helper:
<select asp-for="/*YourProperty*/"
asp-items="#((IEnumerable<SelectListItem>)ViewData["LecturersId"]))">
</select>
Solution for SelectList
If you are keen on the SelectList, make sure that you have provided the dataValueField and dataTextField according to this constructor
public SelectList (System.Collections.IEnumerable items, string dataValueField, string dataTextField);
as below:
ViewData["LecturersId"] = new SelectList(lecturersList, "Value", "Text");
Besides, the query part would be suggested to optimize by joining both tables as below:
var lecturersList = (from a in _context.Lecturer
join b in _context.AcademicDegrees on a.AcademicDegreeId equals b.AcademicDegreeId
select new SelectListItem($"{b.Name} {a.FirstName} {a.LastName}", a.LecturersID.ToString())
).ToList();

How to do this kind of search in ASP.net MVC?

I have an ASP.NET MVC web application.
The SQL table has one column ProdNum and it contains data such as 4892-34-456-2311.
The user needs a form to search the database that includes this field.
The problem is that the user wants to have 4 separate fields in the UI razor view whereas each field should match with the 4 parts of data above between -.
For example ProdNum1, ProdNum2, ProdNum3 and ProdNum4 field should match with 4892, 34, 456, 2311.
Since the entire search form contains many fields including these 4 fields, the search logic is based on a predicate which is inherited from the PredicateBuilder class.
Something like this:
...other field to be filtered
if (!string.IsNullOrEmpty(ProdNum1) {
predicate = predicate.And(
t => t.ProdNum.toString().Split('-')[0].Contains(ProdNum1).ToList();
...other fields to be filtered
But the above code has run-time error:
The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities`
Does anybody know how to resolve this issue?
Thanks a lot for all responses, finally, I found an easy way to resolve it.
instead of rebuilding models and change the database tables, I just add extra space in the search strings to match the search criteria. since the data format always is: 4892-34-456-2311, so I use Startwith(PODNum1) to search first field, and use Contains("-" + PODNum2 + "-") to search second and third strings (replace PODNum1 to PODNum3), and use EndWith("-" + PODNum4) to search 4th string. This way, I don't need to change anything else, it is simple.
Again, thanks a lot for all responses, much appreciated.
If i understand this correct,you have one column which u want to act like 4 different column ? This isn't worth it...For that,you need to Split each rows column data,create a class to handle the splitted data and finally use a `List .Thats a useless workaround.I rather suggest u to use 4 columns instead.
But if you still want to go with your existing applied method,you first need to Split as i mentioned earlier.For that,here's an example :
public void test()
{
SqlDataReader datareader = new SqlDataReader;
while (datareader.read)
{
string part1 = datareader(1).toString.Split("-")(0);///the 1st part of your column data
string part2 = datareader(1).toString.Split("-")(1);///the 2nd part of your column data
}
}
Now,as mentioned in the comments,you can rather a class to handle all the data.For example,let's call it mydata
public class mydata {
public string part1;
public string part2;
public string part3;
public string part4;
}
Now,within the While loop of the SqlDatareader,declare a new instance of this class and pass the values to it.An example :
public void test()
{
SqlDataReader datareader = new SqlDataReader;
while (datareader.read)
{
Mydata alldata = new Mydata;
alldata.Part1 = datareader(1).toString.Split("-")(0);
alldata.Part2 = datareader(1).toString.Split("-")(1);
}
}
Create a list of the class in class-level
public class MyForm
{
List<MyData> storedData = new List<MyData>;
}
Within the while loop of the SqlDatareader,add this at the end :
storedData.Add(allData);
So finally, u have a list of all the splitted data..So write your filtering logic easily :)
As already mentioned in a comment, the error means that accessing data via index (see [0]) is not supported when translating your expression to SQL. Split('-') is also not supported hence you have to resort to the supported functions Substring() and IndexOf(startIndex).
You could do something like the following to first transform the string into 4 number strings ...
.Select(t => new {
t.ProdNum,
FirstNumber = t.ProdNum.Substring(0, t.ProdNum.IndexOf("-")),
Remainder = t.ProdNum.Substring(t.ProdNum.IndexOf("-") + 1)
})
.Select(t => new {
t.ProdNum,
t.FirstNumber,
SecondNumber = t.Remainder.Substring(0, t.Remainder.IndexOf("-")),
Remainder = t.Remainder.Substring(t.Remainder.IndexOf("-") + 1)
})
.Select(t => new {
t.ProdNum,
t.FirstNumber,
t.SecondNumber,
ThirdNumber = t.Remainder.Substring(0, t.Remainder.IndexOf("-")),
FourthNumber = t.Remainder.Substring(t.Remainder.IndexOf("-") + 1)
})
... and then you could simply write something like
if (!string.IsNullOrEmpty(ProdNum3) {
predicate = predicate.And(
t => t.ThirdNumber.Contains(ProdNum3)

ASP.net MVC/EF/C# add none related table records to query in controller

I am trying to add records from table position for positionName(s) to let user select a position for employee when editing.My last attempts is to add a navigation property like field in company model
public virtual ICollection<Position> Mpositions { get; set; }
But all I got so far is null ref exception or no element in viewModel with property "PositionName" ass per viewbag didn't bother using everybody keeps recommending to avoid it so not going to do so either.
public ActionResult Edit([Bind(Include = "CompanyID,CompanyName,EntityForm,Address,Dissolute,CreationDate,FiscaleYear,Description")] Company company)
{
var GlbUpdate = db.Companies.Include(c => c.Members).Include(p => p.Mpositions);
List<Company> mdlCompanies = new List<Company>();
foreach (var item in GlbUpdate)
{
if ((item.Mpositions==null) || (item.Mpositions.Count() == 0))
{
item.Mpositions = (ICollection<Position>)new SelectList(db.Positions.Except((IQueryable<Position>)db.Positions.Select(xk => xk.Members)), "PositionID", "PositionName");
}
mdlCompanies.Add(item);
//I tried first to edit the Mpositions property directly in gblUpdate
//item.Mpositions = (IEnumerable<Position>)db.Positions.Select(p => new SelectListItem { Value = p.PositionID.ToString(), Text = p.PositionName}) ;
//(ICollection<Position>)db.Positions.ToListAsync();
}
In the view I have this
List<SelectListItem> mPositionNames = new List<SelectListItem>();
#*#this yields no results if I try gettign it from the compani record itself it gives a logic error where all id match all positionNames impossible to select an item and only positions already registered are available on the dropDownlist*#
#{foreach (var item in Model.Mpositions)
{
mPositionNames.Add(new SelectListItem() { Text = item.PositionName, Value = item.PositionID.ToString(), Selected = (false) ? true : false });
#*#selected attribute set to false not an issue, no data to select from :p so far*#
}
}
#*#null exception(if i try to midify Mpositions directly in controler) here or empty list if modify it then put it with original query in a new list*#
<div class="SectionContainer R-sectionContainerData" id="MwrapperDataRight">
#Html.DropDownListFor(mpos => item.PositionID, (SelectList)Model.Mpositions)
</div>
All I want to do is pull the positions table to create a drop downList so users can change the position of an employee but since position has a 1>many relation with employee not companies it is not bound automatically by EF nor I seem to be able to use Include() to add it.
Your query for editing positions are complex. This query must edit person's info only. Using Edit action for formalizing position's edit are not correct.It's againts to Single Responsibility Principle. Use ViewComponents for this situation. Load positions separately from person info.
I found a suitable solution using a model that encapsulate the other entities then using Partialviews/RenderAction so each part handles one entity/operation.

Selecting Multiple Linq Fields Removing Column Names

I need to select multiple fields into an enumerator to run a foreach in my Razor web app.
In the controller, I have:
...
cols = (from b in a.RefTable select new {b.Col1,b.Col2,b.Col3}),
...
It returns the values correctly when I use:
#foreach(var col in #item.cols)
{
#col
}
However, the representation on the page is:
{ Col1 = col1Value, Col2 = col2Value, Col3 = col3Value }
Two things I want to do:
Only show the column values on the page without being comma separated (will be separated onto each line within a dataTable field), and then not to show any value if the "col2Value", for example, is blank.
Edit:
Created a new ViewModel to resolve this, e.g.:
public class ColViewModel
{
public string Col1 {get;set;}
...
}
And replaced the Linq with:
...
cols = from b in a.RefTable select new ColViewModel{Col1 = b.Col1, ...},
...
Then, using the example from #Sacrilege below, I'm able to get the strings in the format I need them in.
What you are seeing is the string representation of the object you asked the view to render. You'll need to render each value separately to get your desired output.
#foreach(var col in item.cols)
{
if (!string.IsNullOrEmpty(col.Col1))
{
<div>#col.Col1</div>
}
if (!string.IsNullOrEmpty(col.Col2))
{
<div>#col.Col2</div>
}
if (!string.IsNullOrEmpty(col.Col3))
{
<div>#col.Col3</div>
}
}
You didn't mention the types for each of those fields but I guessed from your comment about them being blank that they were strings. I also added the extra markup because you wanted them each to appear on a separate line and that was a straight forward and easily maintainable way to do so.
#col is an Anonymous Type. So you must access the properties by using #col.Col1 etc. Because this is not supported in razor views in combination with Anonymous Types, you must convert it to an ExpandoObject in order to access the properties.
Take a look here for an example Dynamic Anonymous type in Razor causes RuntimeBinderException

MVC EF layering the code correctly and how to fix navigation naming when updating models from database

I have a two questions.
The first one is about that moment when you go to EDM and update your models from database and it rewrites the old models, losing everything you edited inside them. I read a little about this and it is said that you can create another models and make them also partial and there you may put again the fields so at the next update it won't affect your last changes. How can I do this? I have a separate project for my DAL and the models were generated from database (I have an EDM).
The second question is... But better I give an example. I have a model called Categories and another one CategoriesTranslations, both of them mapped from my database. Let's say you want to have a list of this categories inside a DropDownList() in many views of your website (of your different controllers). The DropDrown will have the value containing the translation which depends on the current language and the keys containing the category ID.
Here is an example of my list:
List<SelectListItem> listItems = new List<SelectListItem>();
var CategoriesTexts = db.Categories.Include(i => i.CategoryTexts).ToList();
foreach (var cat in CategoriesTexts)
{
var texts = cat.CategoryTexts.Where(w=>w.Language.Format == (string)Session["chosen_language"]).FirstOrDefault();
listItems.Add(new SelectListItem
{
Text = texts == null ? cat.Id.ToString() : texts.Name,
Value = cat.Id.ToString(),
});
}
Where should I put this code in my website structure (or how can I structure it) to make use of it in most of my Views?
Thank you!
For your first question
There is no need to make partial classes just to fix the naming when you update EF EDMX file. Actually you shouldn't delete the model class from the Edmx when you make update to your database all you need to do is to update the model and it will save your navigation properties names as you made them already.
For your second Question
Although I don't agree with you about what you're doing to get the categories to the DropDownList, But you could make this as Extension method for the IEnumerable<Category> and put this method in ViewModelExtensions project
e.g.
public static IList<SelectListItem> ToDropDownList(this IEnumerable<Category> query)
{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var cat in query)
{
var texts = cat.CategoryTexts.Where(w=>w.Language.Format == (string)Session["chosen_language"]).FirstOrDefault();
listItems.Add(new SelectListItem
{
Text = texts == null ? cat.Id.ToString() : texts.Name,
Value = cat.Id.ToString(),
});
}
}
then just call it in your controllers like this:
var list = db.Categories.Include(i => i.CategoryTexts).ToDropDownList();

Categories