I have a controller action which returns StudentID.
[HttpPost()]
public ActionResult DisplayStudents()
{
StudentDataContext db = new StudentDataContext ();
var StudentID = (from s in db.vwStudents.Where(s => s.StudentID != null)
group s by s.StudentID into g
select g.Key).ToList();
return Json(new {StudentID});
}
I want to return "StudentName" from the same view as well, but parse the final result and return "StudentID - StudentName" for e.g. "JD11212 - John Deat"
Is there a way where I can group two columns "StudentID" and "StudentName" in one and return that?
...
group s by new {s.StudentID, s.StudentName} into g
...
This will create a new anonymous type {StudentID, StudentName} which should be what you are looking for.
Related
I am new to .NET and I would like to be able to solve this small problem that I am facing. I want to access a list that is in Info method to be able to use it in InfoCurricular method. I do not know how I can do it, if I create a method if doing everything in one is the best. The methods are separated because they have different attributes which result in different results after the action taken.
Info Method
public async Task<IActionResult> Info(string anoLetivo) {
var nomeuc = new List<NomeUC>();
Main main = new Main();
main.NomeUC = nomeuc;
//user
var user = await GetCurrentUserAsync();
//docente
var IDdocente = _context.Docente.SingleOrDefault(x => x.UserId == user.Id);
var nomeporano = (from nome in _context.NomeUC
join unidadecurric in _context.UnidadeCurricular on nome.NomeUCId equals unidadecurric.NomeUCId
join depart in _context.Departamento on unidadecurric.DepartamentoId equals depart.DepartamentoId
join doc in _context.Docente on depart.DepartamentoId equals doc.DepartamentoId
join nalunos in _context.NAlunos on unidadecurric.UnidadeCurricularId equals nalunos.UnidadeCurricularId
join anoletivo in _context.AnoLetivo on nalunos.AnoLetivoId equals anoletivo.AnoLetivoId
where anoletivo.Ano == anoLetivo && doc.DepartamentoId == IDdocente.DepartamentoId
select new {
nome=nome.Nome
}).ToList();
foreach (var item in nomeporano) {
nomeuc.Add(new NomeUC {
Nome = item.nome
});
}
return View("InfoCurricular", main);
}
InfoCurricular Method
public async Task<IActionResult> InfoCurricular(int ano, int semestre) {
var nomeuc = new List<NomeUC>();
//var docente = new List<Docente>();
var unidadecurr = new List<UnidadeCurricular>();
Main main = new Main();
//main.Docente = docente;
main.UnidadeCurricular = unidadecurr;
main.NomeUC = nomeuc;
//user
var user = await GetCurrentUserAsync();
//docente
var IDdocente = _context.Docente.Where(x => x.UserId == user.Id).ToList();
var uc = (from nome in *nomeporano*
join unidadecurric in _context.UnidadeCurricular on nome.NomeUCId equals unidadecurric.NomeUCId
where unidadecurric.AnoCurricular == ano && unidadecurric.Semestre == semestre
select new {
nome = nome.Nome
}).ToList();
foreach(var item in uc) {
nomeuc.Add(new NomeUC {
Nome = item.nome
});
}
return View(main);
}
In the InfoCurrilar method in the uc variable I want to use in the query the values of the other list that is in the Info method and from these values get a new list after executing the query.
The idea is not to get the list in the two methods but use the nomeporano list as a way of going there to seek values.
But this "nomeporano" have attributes that are different in this two methods. I'm still a little bit confused on how to build the method. In Info method the attribute is one, but in InfoCurricular there are two attributes which is different from the other method. How to build a method to retrieve this "nomeporano" list and use that list in methods Info and InfoCurricular? I can undestrand the ways but i'm stuck on the way to build the method .....
There are 2 ways of doing it:
1.) Add a property in the Model class "Main" for retaining complete value of nomeporano, and since you are passing the model to method InfoCurricular, it can easily be used.
2.) Move the below code in the separate method and call the method in methods Info and InfoCurricular:
Cons: Hitting the database multiple times for same data.
var nomeporano = (from nome in _context.NomeUC
join unidadecurric in _context.UnidadeCurricular on nome.NomeUCId equals unidadecurric.NomeUCId
join depart in _context.Departamento on unidadecurric.DepartamentoId equals depart.DepartamentoId
join doc in _context.Docente on depart.DepartamentoId equals doc.DepartamentoId
join nalunos in _context.NAlunos on unidadecurric.UnidadeCurricularId equals nalunos.UnidadeCurricularId
join anoletivo in _context.AnoLetivo on nalunos.AnoLetivoId equals anoletivo.AnoLetivoId
where anoletivo.Ano == anoLetivo && doc.DepartamentoId == IDdocente.DepartamentoId
select new {
nome=nome.Nome
}).ToList();
Regards,
Rajiv
Happy Coding
I wrote a simple select to find searched data in a database. Thing is, in my case when there is no item in the database, method is returning an empty json.
[Route("api/Atributes/{value}")]
public IHttpActionResult GetAtributeByValue(string value)
{
var atribute = ( from a in db.Atributes
join p in db.Cards on a.Atr_Nr equals p.Card_Nr
where a.Atr_Value == value
select new Employee
{
Name = p.Name,
Surname = p.Surname,
Number = a.Atr_Value
});
//this is statement id not working
if (atribute == null)
{
return NotFound();
}
return Ok(atribute);
}
Question is: Is this method of searching correct? If not how should I make it in another way?
Convert your result set to List and use its length property to check. LINQ has deferred execution. Fetch the actual result set with .ToList().
[Route("api/Atributes/{value}")]
public IHttpActionResult GetAtributeByValue(string value)
{
var atribute = ( from a in db.Atributes
join p in db.Cards on a.Atr_Nr equals p.Card_Nr
where a.Atr_Value == value
select new Employee
{
Name = p.Name,
Surname = p.Surname,
Number = a.Atr_Value
}).ToList();
//use count, if that does not work, length here
if (atribute.Count() == 0)
{
return NotFound();
}
return Ok(atribute);
}
Seem like that the method is trying to a list of Atribute. So you just return atribute directly
[Route("api/Atributes/{value}")]
public IHttpActionResult GetAtributeByValue(string value)
{
var atribute = ( from a in db.Atributes
join p in db.Cards on a.Atr_Nr equals p.Card_Nr
where a.Atr_Value == value
select new Employee
{
Name = p.Name,
Surname = p.Surname,
Number = a.Atr_Value
});
return Ok(atribute);
}
EDIT:
Why not 404 (Not Found) ?
The 404 status code should be reserved for situations, in which a resource is not found. In this case, your resource is a collection of Atribute. This collection exists but it's currently empty. It is very confused as an author of a client for your application if I got a 200 one day and a 404 the next day just because someone happened to remove a couple of Atributes. What am I supposed to do? Is my URL wrong? Did someone change the API and neglect to leave a redirection.
public List<Detail> GetOrderDetails()
{
var orderDetails = (from user in db.Users
join detail in db.OrderDetails
on user.Id equals detail.UserId
where (detail.DateAdded != null)
select new Detail
{
FirstName = user.FirstName,
LastName = user.LastName,
Origin = detail.OriginCode,
Destination = detail.DestinationCode,
CarrierCode = detail.CarrierCode,
IsReturn = detail.IsReturn,
IsCancel = detail.IsCancel,
OrderId = detail.OrderId
}).FirstOrDefault();
return Json(orderDetails);
}
This code gives me the following error.
Cannot implicitly convert type 'System.Web.Mvc.JsonResult' to
'System.Collections.Generic.List<TravelingAdmin.Controllers.Detail>
Problems:
(your query).FirstOrDefault(); returns an element not a list.
Json(x) converts x to string which contains json representation of x.
Here are your options:
You can remove FirstOrDefault() and use return (your query).ToList() if you want to return list of objects.
You can change the return type of method to Detail instead of List<Detail> and then use return orderDetails; instead of return Json(orderDetails);
UPDATE:
As inferred from title of the question you want to "return list in json in MVC Controller"
You should change the method to this
public ActionResult GetOrderDetails()
{
var orderDetails = (from user in db.Users
join detail in db.OrderDetails
on user.Id equals detail.UserId
where (detail.DateAdded != null)
select new Detail
{
FirstName = user.FirstName,
LastName = user.LastName,
Origin = detail.OriginCode,
Destination = detail.DestinationCode,
CarrierCode = detail.CarrierCode,
IsReturn = detail.IsReturn,
IsCancel = detail.IsCancel,
OrderId = detail.OrderId
}).ToList();
return Json(orderDetails, JsonRequestBehavior.AllowGet);
}
Just change your return type to JsonResult And use .tolist() method to convert in to list return Json(orderdetails.tolist(),jsonrequestbehaviour.allowget) it's depend on your request if you send request Through "Post" method then use [httppost] attribute on the top of method name and remove "jsonrequestbehaviour.allowget" from your code, it will work for you.
I have 3 tables Project, Province, ProjProvRel
In my project page when I add data I select multiple provinces for each project
means my Province is multi select dropdown list.
I insert data it is working I get the inserted Id and added to ProjProvRel with selected Ids of Province
Now In details view I want to display my data but I could not solve it.
here is my code:
// GET: Project/Details/5
public ActionResult Details(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var mydata = db.Projects.Find(id);
if (mydata == null)
{
return HttpNotFound();
}
var prov_id = from o in db.ProRel where o.ProjectId.Equals(id) select o.ProvinceIds;
foreach (var p_id in prov_id)
{
int[] PIds = new int[] {p_id};
}
var Prov= from c in db.Provinces where c.ID in pIds;
ViewBag.Province = Prov;
return View(mydata);
}
one problem is how can I select data from table based on where condition
var prov_id = from o in db.ProRel where o.ProjectId.Equals(id) select o.ProvinceIds;
is the above query correct ? I am new to ASP.Net MVC
also blow query is correct ?
var Prov= from c in db.Provinces where c.ID in pIds;
how can I select data from Table Province where province.ID in PIds
Get the rows from ProRel where the ProjectId matches with id:
var prov_ids = db.ProRel.Where(r => r.ProjectId == id).Select(r => r.ProvinceId);
Get the provinces that can be found from prov_id:
var provs = db.Provinces.Where(p => prov_id.Any(i => p.ID == i));
I hope you don't mind the lambda-style LINQ.
Also, I think you should consider your variable naming. For example, prov_id gives the idea of a single id and since you declared the type implicitly it is difficult to tell otherwise.
There is a table name Product:
|ProductID|ProductName|
1 abc
2 xyz
and there is another table Product Status.
The column Result in the below has three values:
Result
Value | Meta
0 Not checked
1 Failed
2 Passed
ProductCheckList
ID(AutoGenerated) | ProductID(Foreign Key) | Stage | Result |
1 1 1 1
2 1 2 2
In this table every product has to go through five different stages. If the product passes all the stages then the product is given quality checked status , If the product fails any on of the stages is is given as quality failed and send back to production.
I have to show a list of all the products with there quality status and depending on its quality state highlight the row with different row color. We are using Entity Framework and I am new to this.
I have thought of making a wrapper class for this.
Public class ProductWrapper
{
public Product product{get;set;}
Public string QualityStatus{get;set;}
public string BgColor {get;set;}
}
I am writing this LINQ query:
UtilitiesEntities context = new UtilitiesEntities();
List<ProductWrapper> wrapperList = new List<ProductWrapper>();
var request = from product in context.Product
join productCheck in context.ProductCheckList
on product.productId equals productCheck .productID
// may be do group by or something i get the result and assign the values.
select new List<ProductWrapper>
{
};
I am not able to write the query and add the where condition to fetch the result a list of wrapper class to pass to my view with the desired result.
If I understood correctly your request, you want something like this:
string goodQualityColor = "Green";
string badQualityColor = "Red";
string notCheckedColor = "Gray";
string notCheckedStatus = "Not Checked";
string failedStatus = "Failed";
string passedStatus = "Passed";
Dictionary<int,string> results= new Dictionary<int,string>();
results.Add(2,goodQualityColor);
results.Add(1,badQualityColor);
results.Add(0,notCheckedColor);
Dictionary<int,string> qualityStatuses = new Dictionary<int,string>();
results.Add(2,passedStatus);
results.Add(1,failedStatus);
results.Add(0,notCheckedStatus);
var request = (from product in context.Product
join productCheck in context.ProductCheckList
on product.productId equals productCheck.productID
select new
{
Product = product,
QualityStatus = productCheck.Result,
Result = productCheck.Result
}).ToList();
var finalResults = (from req in request
select new ProductWrapper
{
Product = req.Product,
QualityStatus = qualityStatuses.FirstOrDefault(s => s.Key == req.QualityStatus).Value,
BgColor = results.FirstOrDefault (s => s.Key == req.Result).Value
}).ToList<ProductWrapper>();
I would create an outer join using the into keyword and then do my statusCheck in the select part.
Could would look something like this :
var data = (from product in context.Product
join productCheck in context.ProductCheckList on product.productId equals productCheck.productID into productChecks
select new ProductWrapper
{
product = product,
passedBool = productChecks.All(pc => pc.Result == 2) && productChecks.Count() == 5
}).ToList();