Issue while calling Controller Method - asp.net-mvc

I have two controllers called FormController and CorticonResponseController.
FormController:
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
Session["CorticonServiceEndpoint"] = this.CorticonServiceEndpoint;
Session["CorticonServiceName"] = this.CorticonServiceName;
Session["CorticonServiceMajorVersion"] = this.CorticonServiceMajorVersion;
Session["CorticonServiceMinorVersion"] = this.CorticonServiceMinorVersion;
Session["payLoad"] = “Test”;
return RedirectToAction("CorticonIndex ", “CorticonResponseController”);
}
CorticonResponseController:
public ActionResult CorticonIndex()
{
string payLoad = (string)Session["payLoad"];
string CorticonServiceEndpoint = (string)Session["CorticonServiceEndpoint"];
string CorticonServiceName = (string)Session["CorticonServiceName"];
string CorticonServiceMajorVersion = (string)Session["CorticonServiceMajorVersion"];
string CorticonServiceMinorVersion = (string)Session["CorticonServiceMinorVersion"];
var viewModel = this.Model.GetViewModel(payLoad);
return View ("Default", viewModel);
}
Here, I was sending some information from FormController to CorticonResponseController. In CorticonResponseController, I made some calculations and returning the view with the model.
Hence the URL is changing from http://localhost:35583/banking/open-an-account To http://localhost:35583/banking/open-an-account/CorticonIdex.
However, I don’t want to change the URL so I have modified my code as below.
CorticonResponseController:
public void CorticonIndex()
{
string payLoad = (string)Session["payLoad"];
string CorticonServiceEndpoint = (string)Session["CorticonServiceEndpoint"];
string CorticonServiceName = (string)Session["CorticonServiceName"];
string CorticonServiceMajorVersion = (string)Session["CorticonServiceMajorVersion"];
string CorticonServiceMinorVersion = (string)Session["CorticonServiceMinorVersion"];
var viewModel = this.Model.GetViewModel(payLoad);
TempData["ResponseController"] = viewModel;
}
FormController:
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
Session["CorticonServiceEndpoint"] = this.CorticonServiceEndpoint;
Session["CorticonServiceName"] = this.CorticonServiceName;
Session["CorticonServiceMajorVersion"] = this.CorticonServiceMajorVersion;
Session["CorticonServiceMinorVersion"] = this.CorticonServiceMinorVersion;
Session["payLoad"] = “Test”;
CorticonResponseController obj = new CorticonResponseController();
obj.CorticonIndex();
CorticonResponseModel viewModel = (CorticonResponseModel)TempData["ResponseController"];
string controllerName = DecisionServiceProgram.GetResponseWidgetName();
return View("Default", viewModel);
}
Here,In my FormController, I was calling CorticonResponseController method and getting CorticonResponseModel data using TempData and then returning the view.
I am facing the issues while executing the controller.
Can someone help me how to resolve the issue?

Related

Display ads on multiple Views by using single controller method in MVC

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.

object reference not set in combobox with two model view razor

I tried to create more than one combobox, but model to view combobox is different. then I tried to combine two models in one class, but I get an error "object reference not set to an instance of an object" when I click on the link to go to that page.
please help me to fix the matter. thank you, sorry if I mess sentence.
This piece from some source code :
controller partial combobox ,
[ValidateInput(false)]
public ActionResult cbPartialCategoryDetail(string group)
{
SalesMonitoringDAC modelSM = new SalesMonitoringDAC();
MPMPRODUCTGROUPLINE item = new MPMPRODUCTGROUPLINE();
item.GROUPID = group;
List<string> mpmDetailCat = modelSM.GetProductGroupDetail(group);
return PartialView("_cbPartialCategoryDetail", mpmDetailCat);
}
and this is code combobox partial
#model DIS_iDealer.Models.SalesMonitoringModel
#Html.DevExpress().ComboBoxFor(m => m.mpmGroupLine.DESCRIPTION, settings =>
{
settings.Name = "Desc_ID_CB";
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Report", Action = "cbPartialCategoryDetail" };
settings.Properties.CallbackPageSize = 50;
settings.Properties.ValueField = "DESCRIPTION";
settings.Properties.TextField = "DESCRIPTION";
settings.Properties.ValueType = typeof(string);
settings.Width = 100;
settings.Properties.DropDownWidth = 100;
settings.SelectedIndex = 0;
settings.Properties.ClientSideEvents.BeginCallback = "function(s, e) { e.customArgs['GroupId'] = Category_Id_CB.GetValue(); }";
settings.Properties.ClientSideEvents.SelectedIndexChanged = "OnInitDetailCategory";
settings.Properties.ClientSideEvents.Init = "OnInisialDetailCategory";
settings.Properties.ValidationSettings.ErrorTextPosition = ErrorTextPosition.Right;
settings.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
settings.Properties.ValidationSettings.Display = Display.Dynamic;
settings.Enabled = true;
settings.ShowModelErrors = true;
//}).BindList(ViewBag.DetailCategory).GetHtml()
}).BindList((new DIS_iDealer.DataAccess.SalesMonitoringDAC()).GetProductGroupDetail(Model.mpmGroupLine.GROUPID)).GetHtml()
this is class two combine the two model
namespace DIS_iDealer.Models
{
public class SalesMonitoringModel
{
public MPMPRODUCTGROUPLINE mpmGroupLine { get; set; }
public MPMDataDealer mpmDataDealer { get; set; }
public SalesMonitoringModel(MPMPRODUCTGROUPLINE _mpmGroupLine, MPMDataDealer _mpmDataDealer) {
mpmGroupLine = _mpmGroupLine;
mpmDataDealer = _mpmDataDealer;
}
}
}
Isn't that really strange. In your action method you are returning a List<string> as seen below
List<string> mpmDetailCat = modelSM.GetProductGroupDetail(group);
return PartialView("_cbPartialCategoryDetail", mpmDetailCat);
Whereas in your partial view you are expecting a model of type SalesMonitoringModel and that's the source of this error. I am not sure what you are exactly trying to achieve and so can't help beyond this
#model DIS_iDealer.Models.SalesMonitoringModel

mvc3, can you give controller a display name?

I am using mvc3. is it possible to give controller and action a display name.
[DisplayName("Facebook Employee")]
public class EmployeeController : Controller
in my breadcrumb, I will get the controller name and action name
#{
var controllerName = ViewContext.RouteData.Values["Controller"];
var actionName = ViewContext.RouteData.Values["Action"];
}
I expect to see "Facebook Employee", but its not working.
You'll have to reflect on the Controller type itself, using GetCustomAttributes. Use ViewContext.Controller to get a reference to the controller itself. Something like this:
string controllerName;
Type type = ViewContext.Controller.GetType();
var atts = type.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (atts.Length > 0)
controllerName = ((DisplayNameAttribute)atts[0]).DisplayName;
else
controllerName = type.Name; // fallback to the type name of the controller
Edit
To do similar for an action, you need to first reflect on the method, using Type.GetMethodInfo:
string actionName = ViewContext.RouteData.Values["Action"]
MethodInfo method = type.GetMethod(actionName);
var atts = method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
// etc, same as above
public static class HLP
{
public static string DisplayNameController(this WebViewPage wvp)
{
if (wvp.ViewBag.Title != null && (wvp.ViewBag.Title as string).Trim().Length > 0)
return wvp.ViewBag.Title;
ControllerBase Controller = wvp.ViewContext.Controller;
try
{
DisplayNameAttribute[] attr = (DisplayNameAttribute[])Controller.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), false);
string DisplayName = attr[0].DisplayName;
return DisplayName;
}
catch (Exception)
{
return Controller.ToString();
}
}
public static string DisplayNameAction(this WebViewPage wvp)
{
string actionName = wvp.ViewContext.RouteData.Values["Action"].ToString();
try
{
Type type = wvp.ViewContext.Controller.GetType();
MethodInfo method = type.GetMethod(actionName);
DisplayNameAttribute[] attr = (DisplayNameAttribute[])method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
string DisplayName = attr[0].DisplayName;
return DisplayName;
}
catch (Exception)
{
return actionName;
}
}
}
<title>#this.DisplayNameAction()</title>

View doesn't refresh after RedirectToAction is done

Here is my problem:
[HttpPost]
public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
return RedirectToAction("DisplayCandidate",new {id=newCandidateId});
}
public ActionResult DisplayCandidate(int id)
{
var candidateViewModel= this._serviceClient.GetCandidate(id);
return View(candidateViewModel);
}
After filling the form viwemodel sends to server. After data were stored, flow is redirected to DisplayCandidate action and it goes there but page didn't refresh. I don't understand why! Help, please.
Because you are using Ajax Post
public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
string ReturnURL = "/DisplayCandidate/"+newCandidateId;
return JSON(ReturnURL);
}
and in your Ajax Post Method:
Onsuccess(function(retURL){ window.location(retURL); })
This will take to the new Action and that Action will return View.
If you're using Ajax, return a script results to execute the navigation
instead of
return RedirectToAction("DisplayCandidate",new {id=newCandidateId});
try
var viewName = "/Path/ViewName";
var id = 1;
var urlNavigate = string.Format("location.href='{0}?id={1}'", viewName, id);
return new JavaScriptResult() { Script = urlNavigate };

two models in a view - not working for me

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);
}

Resources