I know how to do a where in Qlink... p.e.
public ActionResult Index(){
using (DBEntities db = new DBEntities())
{
return View(db.vw_values.Where(m => m.value == 1).ToList());
}
}
but I want to do a Where in but I´ve not found how to implement it... p.e.
... int[] values = {1,2,3, ...}
return View(db.vw_values.Where(m => m.value == values).ToList()); ...
is it posible? (The idea, I know that this code is wrong)
All you have to do is:
public ActionResult Index()
{
using (DBEntities db = new DBEntities())
{
return View(db.vw_values.Where(m => values.Contains(m.value).ToList());
}
}
Here
you can learn more about LINQ in C# and all the other cool things you can do with it.
Related
I want to return my result as array list. My code looks like this:
public Person Get(string doctorCode)
{
using (PharmaOCEAN_LTEntities entities = new PharmaOCEAN_LTEntities())
{
return entities.Person.FirstOrDefault(e => e.DoctorLicenseNumber == doctorCode);
}
}
Some guy informed me that selected (all) result will be an array, so I tried this way, but im getting an error with select statement:
public IList<Person> Get(string doctorCode)
{
using (PharmaOCEAN_LTEntities entities = new PharmaOCEAN_LTEntities())
{
return entities.Person.Select<Person>(e => e.DoctorLicenseNumber == doctorCode);
}
}
any opinions?
Yeah sure you can!
As a array:
public Person[] Get(string doctorCode)
{
using (PharmaOCEAN_LTEntities entities = new PharmaOCEAN_LTEntities())
{
return entities.Person.Where(e => e.DoctorLicenseNumber == doctorCode).ToArray();
}
}
As a list:
public IEnumerable<Person> Get(string doctorCode)
{
using (PharmaOCEAN_LTEntities entities = new PharmaOCEAN_LTEntities())
{
return entities.Person.Where(e => e.DoctorLicenseNumber == doctorCode).ToList();
}
}
not sure if it compiles, but you get the message :)
Can you provide info error that you get?
Don't you have to add ToList() at the end of select statement?
In my current MVC Project, I have a controller with the following method:
public ActionResult Index(string answer)
{
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == 1).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == 1).Select(s => s.AnsAnswer).ToList();
}
return View(afqList);
}
However, this method is repeated 5 times, all with the only difference being that the number in (w => w.QuQuestionId == x) and (w => w.AnsQuestionId == x) changes, as well as having 5 different, although still similar, views for each method. How would I make this code a lot better than having 5 almost identical methods, but all still having different views? Thanks in advance!
EDIT:
I should also mention that in each of these methods, the corresponding view has a
#using (Html.BeginForm("Question3", "ControllerName", "FormMethod.Post))
and so need to call different methods based on which one comes next and is stated in the views.
Replace the number with x which will be passed as parameter
public ActionResult Index(string answer, int x)
{
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == x).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == x).Select(s => s.AnsAnswer).ToList();
}
return View(afqList);
}
First add to your model:
public string NextQuestion { get; set; }
Then you can use it in your action and view:
public ActionResult Index(string answer, int questionId)
{
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == questionId).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == questionId).Select(s => s.AnsAnswer).ToList();
}
afqList.NextQuestion = string.Format("Question{0}", questionId + 1);
return View(afqList);
}
Now in the View:
#using (Html.BeginForm(afqList.NextQuestion, "ControllerName", "FormMethod.Post))
I'm storing list of string in to a session. Then I don't know how to get those data to display in my view.
This is my code:
public List<Details> d = new List<Details>();
[HttpPost]
public void getDatas(string destination)
{
XElement rootele = XElement.Load(Server.MapPath("~/XmlFiles/CruiseData/cruiseprodutstwo.xml"));
var getneededData = rootele.Elements("CruiseProduct")
.Where(l => l.Element("Location").Value == destination)
.Select(s => s.Element("Name").Value);
foreach (var itm in getneededData)
{
d.Add(new Details
{
cruiseName = itm
});
}
Session["names"] = d;
Response.Redirect("Check",true);
}
This is my check action method
public ActionResult Check()
{
var chk = Session["names"];
return View();
}
You can store your data in ViewBag, then retrieve them in view:
public ActionResult Check()
{
ViewBag.SessionData = Session["names"] as List<DetailsList>;
Return View();
}
Then in your view, use simply as
#If (ViewBag["SessionData"]!= null){
// Do jobs with SessionDetails what you want
}
Hope this helps.
Controller
public ActionResult Check()
{
var chk = Session["names"];
List<Details> list = Session["names"] as List<Details>;
ViewBag.MyList = list ;
return View();
}
View
#ViewBag.MyList
// e.g.
#foreach (var item in ViewBag.MyList) { ... }
Firstly, it is better to use ViewBag, ViewData and/or TempData when playing with MVC.
The use is quite simple for all the three. Here are the steps :
You assign them some value/object : ViewBag.SomeField = SomeValue;
You use them on your view side : #ViewBag.SomeField.
Here are some link that will definitely get you through :
ViewBag ViewData and TempData
ViewBag ViewData and TempData Basics
Since you are redirecting to an action method here, I would suggest using TempData for your case and using that in the view.
Hope this helps.
How do you write an if/else statement for this method if there is no result?
public ActionResult Search(string q)
{
Helpers Helpers = new Helpers();
var restaurants = Helpers.getRestaurant(q);
return View("_RestaurantSearchResults", restaurants);
}
Helpers class contains:
public class Helpers
{
FoodReviewContext _db = new FoodReviewContext();
public static IQueryable<Restaurant> getRestaurant(string q)
{
var restaurents = _db.Restaurants
.Where(r => r.Name.StartsWith(q) || String.IsNullOrEmpty(q))
.Take(2);
return restaurents;
}
}
If I understand your question correctly:
public ActionResult Search(string q)
{
Helpers Helpers = new Helpers();
var restaurants = Helpers.getRestaurant(q);
if (restaurants.Count() == 0) {
// do something
} else {
// do something else
}
return View("_RestaurantSearchResults", restaurants);
}
Take a look here: http://msdn.microsoft.com/en-us/library/bb351562%28v=vs.110%29.aspx. This goes over all the methods in the IQueryable<T> interface.
Oftentimes when you are looking for how to work with a certain part of the .NET Framework, C#, or others' code, the documentation is the best first place to go to.
simply check your result count for it.
public ActionResult Search(string q)
{
Helpers Helpers = new Helpers();
var restaurants = Helpers.getRestaurant(q);
if(restaurants.Count()>0)
{
return View("_RestaurantSearchResults", restaurants);
}
else
{
ViewBag.Message="No result found";
return View("_RestaurantSearchResults");
}
}
And just check if ViewBag.Message is available or not in View.
Try this
if (restaurants.Count() != 0)
{
//non-zero thing
}
else
{
//zero thing
}
I have a UnitOfWork/Service pattern where I populate my model using NHibernate before sending it to the view. For some reason I still get the YSOD, and I don't understand why the object collection is not already populated.
My controller method looks like this:
public ActionResult PendingRegistrations()
{
var model = new PendingRegistrationsModel();
using (var u = GetUnitOfWork())
{
model.Registrations = u.UserRegistrations.GetRegistrationsPendingAdminApproval();
}
return View(model);
}
The service/unit of work looks like this:
public partial class NHUserRegistrationRepository : IUserRegistrationRepository
{
public IEnumerable<UserRegistration> GetRegistrationsPendingAdminApproval()
{
var r =
from UserRegistration ur in _Session.Query<UserRegistration>()
where ur.Status == AccountRegistrationStatus.PendingAdminReview
select ur;
NHibernateUtil.Initialize(r);
return r;
}
}
What am I doing wrong?
The problem you are having is no different than the problem you would have with any other LINQ provider. You need to execute your query in order to get the results. If you don't have a valid context, that won't work.
This problem is easy to fix without condemning LINQ to NHibernate. Just change
public IEnumerable<UserRegistration> GetRegistrationsPendingAdminApproval()
{
var r =
from UserRegistration ur in _Session.Query<UserRegistration>()
where ur.Status == AccountRegistrationStatus.PendingAdminReview
select ur;
NHibernateUtil.Initialize(r);
return r;
}
to
public IEnumerable<UserRegistration> GetRegistrationsPendingAdminApproval()
{
var r =
from UserRegistration ur in _Session.Query<UserRegistration>()
where ur.Status == AccountRegistrationStatus.PendingAdminReview
select ur;
NHibernateUtil.Initialize(r);
return r.ToList();
}