How can I throw a sql query into the Viewbag - asp.net-mvc

Hi I have 2 tables in my database. I want to compare and list the news items in table A that are not in table B.
I wrote a sql query.
SELECT ID FROM News_TB
where ID not in ( select News_ID From Slider_TB)
I need a Viewbag that uses this query to do the listing.On account controller.
MY View Code in Account Controller
public ActionResult SliderCategoryDetay(int ID)
{
var kontrol = _udb.SliderCategoryTB_Select().Where(m => m.SliderCategoryID == ID).First();
ViewData["ID"] = kontrol.SliderCategoryID;
ViewBag.slider = _udb.SliderTB_Select().Where(m => m.SliderID == ID);
ViewBag.sliderhabercek = _udb.NewsTB_Select(); /*THİS*/
return View();
}
I want to do it on this page.Thanks for your help.

you can use viewbag.data like this
public ActionResult SliderCategoryDetay(int ID)
{
var kontrol = _udb.SliderCategoryTB_Select().Where(m => m.SliderCategoryID == ID).First();
ViewData["ID"] = kontrol.SliderCategoryID;
ViewBag.data = kontrol;
ViewBag.slider = _udb.SliderTB_Select().Where(m => m.SliderID == ID);
ViewBag.sliderhabercek = _udb.NewsTB_Select(); /*THİS*/
return View();
}
And in your view use following example
#foreach(var item in ViewBag.data)
{
#item.Value
}

Related

Access data from Viewbag Dropdown

I am getting the value from dropdown to controller but when it goes back to View it returns Null
SCREENSHOT OF VIEW:-
SCREENSHOT OF CONTROLLER:-
public ActionResult Index(int departmentID)
{
ViewBag.dropdowndetail = null;
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.ToList().FirstOrDefault(x=>x.depId==departmentID);
return View(emp);
}
}
ERROR:
I get it right
My viewbag was not getting any value in Post method so that why in View it was getting null Exception
I call my viewbag in Post method and give it the value.
change the following code with this.
public ActionResult Index(int departmentID)
{
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.Where(x=>x.depId==departmentID).ToList();
ViewBag.dropdowndetail = db.departments.Distinct().ToList();
return View(emp);
}
}
You can use keyvalue approach in controller
ViewBag.dropdowndetail = db.departments.Distinct().Select(x => new KeyValuePair<int, string>(x.depid, x.DepartmentName));
and in View use ViewBag like this
#Html.DropDownListFor(model => model.depid, new SelectList((IEnumerable<KeyValuePair<int, string>>)ViewBag.dropdowndetail , "key", "value"), "--Select Departments--")

return relational data list to partial view

I wanted to return a list to my partial view from relational matching data of products. I have attached picture of edmx file where you will get idea about their relationship status! Problem is i just dont know how can i write this query or i need any iteration process to do it. Main goal is: I want to get all Products that the current user has bookmarked. Any question welcome. Thanks in advance
[ChildActionOnly]
[Authorize]
public PartialViewResult _UserBookmark(string id)
{
using (mydb db = new mydb())
{
int userId = db.Users.Where(x => x.Email == id).FirstOrDefault().UserId;//here i am getting user primary key id
var ProductIds = db.Bookmarks.Where(x => x.UserId == userId).ToList();//here i am getting all Product primary keys under that user
var ListOfProducts = db.Products.Where(x=>x.ProductId == "i dont know how to do it") // here i wanted to return matched all products
return PartialView("_UserBookmark",ListOfProducts);
}
}
You can use a .Contains statement to return the Products where the ProductId is in your collection of ProductIds.
Change the method to
[ChildActionOnly]
[Authorize]
public PartialViewResult _UserBookmark(string id)
{
using (mydb db = new mydb())
{
int userId = db.Users.Where(x => x.Email == id).FirstOrDefault().UserId;
// Get a collection of the ProductId's
IEnumerable<int> ProductIds = db.Bookmarks
.Where(x => x.UserId == userId).Select(x => x.ProductId);
IEnumerable<Product> ListOfProducts = db.Products
.Where(x => ProductIds.Contains(x.ProductId))
return PartialView("_UserBookmark", ListOfProducts);
}
}
Note, if the results are for the current user, then consider just getting the current user in the method rather that passing their Email to the method. Note also that .FirstOrDefault().UserId would throw an exception is you passed an incorrect value to the method which resulted in User being null.

LINQ Select Query with Where Condition Which returns single record

public ActionResult CreateArea(int? cityid)
{
if (cityid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Name = db.Cities.Where(c => c.CityID == cityid)
.Select(x => x.CityName);
ViewBag.message = Name;
Area city = db.Areas.Find(cityid);
return View(city);
}
This my ActionMethod in this i want cityname which i m passing to view through viewbag but my LINQ query is wrong it not displaying cityname instead of this query is printing to my view.plz help me to correct my LINQ query.
You're missing the "execution" of the "expression" like .ToList(), .First(), .FirstOrDefault(), .Single() .....
var name = db.Cities.Where(c => c.CityID == cityid).Select(x => x.CityName).FirstOrDefault();
var Name = db.Cities.Select(x => x.CityName).Where(c => c.CityID == cityid).FirstOrDefault()
ViewBag.message = Name;
Area city = db.Areas.Find(cityid);
return View(city);
try something like this
You need to return the single result from the query and then access the name property:
var Name = db.Cities.Single(c => c.CityID == cityid).CityName;
This may help you!
var model = model.Where(i => i.ParamKey == Key).First();

MVC C# Select Where

I am trying to add filter by ID for the following:
public ActionResult Index()
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
What I would like to do is the following:
public ActionResult Index(long? id)
{
if (id != null)
{
var model = from o in new MainDBContext().OffLinePayments
**Where Assigned_ID == id**
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
else
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
}
try
var model = from o in new MainDBContext().OffLinePayments
where o.Assigned_ID == id
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
If I understand correctly, your problem is that the compiler doesn't let you write where o.Assigned_ID == id in the query.
That's because id is a Nullable<long>, which is not implicitly convertible to a long (which OffLinePayment.Assigned_ID presumably is).
You need to write where o.Assigned_ID == id.Value instead. Take a look at what the Value property does so that you don't get any surprises.
A cleaner, shorter and much more readable syntax would look like this:
public ActionResult Index(long? id){
using (var ctx = new MainDBContext())
{
var entities = ctx.OfflinePayments.Where(e => !e.HasValue || e.Assigned_ID == id.Value);
var model = entities.Select(e => new EditOfflinePayment { ID = e.ID, Amount = e.Amount }).ToList();
return View(model);
}
}

Passing and receiving routedictionary values in mvc2

I have a link in my action like this
<%: Html.ActionLink("View Data","Index","MyItem", new {itemId=Model.itemId}, null)%>
now in my newItem controller in its index action how do I retrieve this itemId, so far I have tried
this
public ActionResult Index()
{
RouteData rd = this.RouteData;
var list = from p in rd.DataTokens.Where(p => p.Key == "itemId") select p;
int? id = null;
if (list.Count() > 0)
id = Convert.ToInt32(list.Single().Value);
if (id.HasValue)
{
return View(from a in _Service.List().Where(a => a.ApplicantId == id.Value) select a);
}
else
return View(NORECORDVIEW,);
}
and also this
HttpRequestBase rd = this.Request;
var list = from p in rd.QueryString.AllKeys.Where(p => p. == "itemId") select p;
int? id = null;
if (list.Count() > 0)
id = Convert.ToInt32(list.Single().Value);
if (id.HasValue)
{
return View(from a in Service.List().Where(a => a.ApplicantId == id.Value) select a);
}
else
return View(NORECORDVIEW);
however none of this return the correct value.
In mvc1 we could easily handle that directly but how do you do this in mvc2 please.
You can do this much more easily:
public ActionResult Index(int itemId)
Not only is this 1/10th the code, it's far more easily tested.

Resources