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.
Related
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--")
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
}
I have created an entity data model from my database. however in certain areas of the application i need to pass two models. thus i create a third model which has as properties the objects of each required model.
In the scenario, i want to use one model just to show some data to the user and the other is to be populated by the user using form elements. therefore, i create a constructor in my custom model to populate it. here's the code:
THE CUSTOM MODEL
public class ordersModel
{
public ordersModel(order or)
{
this.prods = new order_products();
this.new_order = new order();
this.new_order.customer_id = or.customer_id;
this.new_order.my_id = or.my_id;
this.new_order.my_order_id = or.my_order_id;
this.new_order.order_date = or.order_date;
this.new_order.order_status_id = or.order_status_id;
}
public order new_order { get; set; }
public order_products prods { get; set; }
}
IT IS USED IN THE CONTROLLER AS FOLLOWS:
public ActionResult Create()
{
order or = new order();
// Store logged-in user's company id in Session
//or.my_id = Session["my_id"].ToString();
//do something to allow user to select customer, maybe use ajax
or.customer_id = "123";
or.order_amount = 0;
or.my_id = "74973f59-1f6c-4f4c-b013-809fa607cad5";
// display date picker to select date
or.order_date = DateTime.Now.Date;
// fetch statuses from database and show in select list box
or.order_status_id = 1;
return View(or);
}
//
// POST: /Orders/Create
[HttpPost]
public ActionResult Create(order or)
{
using (invoicrEntities db = new invoicrEntities())
{
var temp = db.last_order_number.SingleOrDefault(p => p.my_id == or.my_id);
if (temp != null)
{
or.my_order_id = temp.my_order_id + 1;
if (ModelState.IsValid)
{
ordersModel ord = new ordersModel(or);
db.orders.AddObject(or);
temp.my_order_id = temp.my_order_id + 1;
//TempData["my_order_id"] = or.my_order_id;
db.SaveChanges();
return RedirectToAction("AddProducts", ord);
//return RedirectToAction("AddProducts", new { id = or.my_order_id });
}
return View(or);
}
return RedirectToAction("someErrorPageDueToCreateOrder");
}
}
public ActionResult AddProducts()
{
using (invoicrEntities db = new invoicrEntities())
{
//string my_id = TempData["my_id"].ToString();
//string my_order_id = TempData["my_order_id"].ToString();
string my_id = "74973f59-1f6c-4f4c-b013-809fa607cad5";
int my_order_id = 1;
//Int64 my_order_id = Convert.ToInt64(RouteData.Values["order_id"]);
// Display this list in the view
var prods = db.order_products.Where(p => p.my_id == my_id).Where(p => p.my_order_id == my_order_id).ToList();
var or = db.orders.Where(p => p.my_id == my_id).Where(p => p.my_order_id == my_order_id).ToList();
if (or.Count == 1)
{
//ViewData["name"] = "sameer";
ViewData["products_in_list"] = prods;
ViewData["order"] = or[0];
return View();
}
return RedirectToAction("someErrorPageDueToAddProducts");
}
}
[HttpPost]
public ActionResult AddProducts(order_products prod)
{
prod.my_id = "74973f59-1f6c-4f4c-b013-809fa607cad5";
// find a way to get the my_order_id
prod.my_order_id = 1;
return View();
}
THIS ALL WORKS OUT WELL, UNTIL IN THE "ADDPRODUCTS" VIEW:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<invoicr.Models.ordersModel>" %>
AddProducts
<h2>AddProducts</h2>
<%: Model.new_order.my_id %>
the above statement gives an error
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
what am i doing wrong here?
You seem to be passing the wrong model when redisplaying your Create view.
Try passing the ord instance which is of type ordersModel and which is what your view is strongly typed to:
public ActionResult Create(order or)
{
using (invoicrEntities db = new invoicrEntities())
{
var temp = db.last_order_number.SingleOrDefault(p => p.my_id == or.my_id);
if (temp != null)
{
or.my_order_id = temp.my_order_id + 1;
ordersModel ord = new ordersModel(or);
if (ModelState.IsValid)
{
db.orders.AddObject(or);
temp.my_order_id = temp.my_order_id + 1;
db.SaveChanges();
return RedirectToAction("AddProducts", ord);
}
return View(ord);
}
return RedirectToAction("someErrorPageDueToCreateOrder");
}
}
UPDATE:
Now that you have shown your AddProducts action you are not passing any model to the view although your view expects an ordersModel instance. So don't just return View();. You need to pass an instance of ordersModel:
if (or.Count == 1)
{
ViewData["products_in_list"] = prods;
ViewData["order"] = or[0];
ordersModel ord = new ordersModel(or[0]);
return View(ord);
}
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);
}
}
I'm new to asp.net mvc. I have index method with parameter id :
public ActionResult Index(int id)
{
var dc = new ServicesDataContext();
var query = (from m in dc.Mapings
where m.CustomerID == id
select m);
// var a = dc.Customers.First(m => m.CustomerId == id);
// ViewData.Model = a;
// return View();
return View(query);
}
Now when I try to redirect to index from edit i get an error " The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MVCServices.Controllers.CustomerserviceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
[HttpPost]
public ActionResult Edit( FormCollection form)
{
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());
if (ModelState.IsValid)
{
try
{
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { qw = qw });
}
catch{
}
}
return View(serviceToUpdate);
}
This is the View:
#Html.ActionLink("Back to List", "Index")
The id in the Index method turns out to be the customerid fetched from another controller while id in Edit is from another table.Can you please let me know the mistake I've been doing and how to solve it?
Do this in the Edit action:
return RedirectToAction("Index", new { id = qw });