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--")
Related
I want to display different ads on multiple Views from single method. Currently, I have created separate controller method for the ads and then passing page name by using session from each View's controller method. I want to get rid off any code related to ads from each controller method.
Please suggest me way to do this.
Home controller
public ActionResult Index()
{
ClsHomeContent model = new ClsHomeContent();
List<Advertisement> advertList = new List<Advertisement>();
var context = new ApplicationDbContext();
var advert = context.Advertisement.ToList();
var pageName = context.Advertisement.Where(x => x.Page == "Home").Select(y => y.Page).FirstOrDefault();
Session["PageName"] = pageName;
return View(model);
}
HorseTracker Controller
public ActionResult HorseTracker()
{
List<Advertisement> advertList = new List<Advertisement>();
var advert = context.Advertisement.ToList();
var pageName = context.Advertisement.Where(x => x.Page == "HorseTracker").Select(y => y.Page).FirstOrDefault();
Session["PageName"] = pageName;
return View(model);
}
Then using this session value
public ClsAdvertisment advertPosition()
{
List<Advertisement> advertList = new List<Advertisement>();
ClsAdvertisment model = new ClsAdvertisment();
var context = new ApplicationDbContext();
var advert = context.Advertisement.ToList();
foreach (var advertisementData in advert)
{
if (advertisementData.Position == Session["PageName"] + "_Top_Left" || advertisementData.Position == Session["PageName"] + "_Top_Right" || advertisementData.Position == Session["PageName"] + "_Middle" || advertisementData.Position == Session["PageName"] + "_Left")
{
advertList.Add(new Advertisement()
{
AdvertId = advertisementData.AdvertId,
Position = advertisementData.Position,
FilePath = advertisementData.FilePath,
Hemisphere = advertisementData.Hemisphere,
Link = advertisementData.Link,
Title = advertisementData.Title
});
}
}
model.advertisement = advertList;
return model;
}
[ChildActionOnly]
public PartialViewResult Advertisement()
{
var model= advertPosition();
return PartialView("_pAdvertisement", model);
}
Created separate partial view
foreach (var item in Model.advertisement)
{
if (#item.Hemisphere == 1 && item.Position == (string)Session["PageName"]+"_Top_Left")
{
<a href="#item.Link" title="#item.Title" target="_blank">
#Html.Image(item.FilePath, "Image", "", "")
</a>
}
}
You can get the name of the parent controller and action methods in the child method using the ParentActionViewContext property of ControllerContext
[ChildActionOnly]
public PartialViewResult Advertisement()
{
ViewContext context = ControllerContext.ParentActionViewContext;
string controllerName = context.RouteData.Values["controller"].ToString();
string actionName = context.RouteData.Values["action"].ToString();
ClsAdvertisment model = advertPosition(controllerName, actionName);
return PartialView("_pAdvertisement", model);
}
Then modify your advertPosition() to
public ClsAdvertisment advertPosition(string controllerName, string actionName)
and within that method, select the ads to be displayed based on those values, and there is also no need to use Session.
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
}
in HomeController.cs
[HttpPost]
public ActionResult Index(SecurityMappingModel objModel)
{
//edit code
if (objModel.Id != Guid.Empty)
{
if (ModelState.IsValid)
{
mappings = (List<SecurityMappingModel>)Session["Mappings"];
var objRemove = mappings.FirstOrDefault(m => m.Id == objModel.Id);
if (objRemove != null)
{
mappings.Remove(objRemove);
mappings.Add(objModel);
ViewBag.Mappings = mappings;
}
Session["Mappings"] = mappings;
return RedirectToAction("Index");
}
inside objModel one of the field is having value 0 as it is a textfield i'm putting value into it but inside Controller oject objModel showing that field value is zero :( :( why???
if (yourGuid != Guid.Empty)
I also encountered this kind of error.
Maybe the solution to your problem is placing a code like this in your Home.cshtml view:
#Html.HiddenFor(model => model.Id)
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 });
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.