Redirection to different controller method - asp.net-mvc-3

I need to redirect a request to another controller. So basically I have www.MyDomain.com/SomeParameter. I need to read this parameter value from URL and then redirect to another controller for further processing. For this purpose I have two controllers in my project Home and Employee as follows.
public class HomeController : Controller
{
public ActionResult Index(string ID)
{
if (!string.IsNullOrEmpty(ID))
{
string EmployeeAccountNumber = GetEmployeeNumberFromID(ID);
RedirectToAction("Employee", "Index", EmployeeAccountNumber);
}
return View();
}
private string GetEmployeeNumberFromID(string ID)
{
return "Alpha";
}
}
public class EmployeeController : Controller
{
//
// GET: /Employee/
public ActionResult Index(string id)
{
return View();
}
}
I then added Routing is defined as follows in Global.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"EmployeeManagement", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Employee", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
As you can see in the Index method of HomeController class, I want to Redirect to my EmployeeController, however, the breakpoint I set in EmployeeController.Index never get hit. Am I doing something wrong here?

public class HomeController : Controller
{
public ActionResult Index(int id)
{
// Redirect/Index/id is because of route defined as {controller}/{action}/{id}
//if u need the url to be say "www.MyDomain.com/3240" then change route definition as
//"{id}" instead of "{controller}/{action}/{id}". Tested and working
return RedirectToAction("Index", "Redirect/Index/" + id);
}
}
public class RedirectController : Controller
{
//
// GET: /Redirect/
public ActionResult Index(int id)
{
return View();
}
}
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"redirectedroute", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "RedirectController", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Use
return RedirectToAction("Employee", "Index", new {"id"=EmployeeAccountNumber});
instead of
RedirectToAction("Employee", "Index", EmployeeAccountNumber);
You are not passing route parameters

Instead of RedirectToAction() try Redirect("/Employee") and let controller handle rest

Related

How to get route parameter on difference function on laravel?

I have a problem in my project laravel, I want to get route parameter 'id_project' on route 'project' to use in route 'modulproject'. This route in one view.
This is my Route:
Route::get('project/{id_project}','ProjectDetailController#project');
Route::get('modulproject','ProjectDetailController#modulproject');
This is my Controller:
public function project($id_project)
{
$project=Project::where('id','=',$id_project);
return($project);
}
public function modulproject($id_project)
{
$modulproject=Modul::where('id_project','=',$id_project);
return($modulproject);
}
You can used Session to get that id_project.
use Session;
public function project($id_project)
{
Session::put('id_project',$id_project);
$project=Project::where('id','=',$id_project);
return($project);
}
public function modulproject()
{
if(Session::has('id_project')){
$modulproject=Modul::where('id_project','=',Session::get('id_project'));
Session::forget('id_project');
return($modulproject);
}
else{
return 'redirect to other page.. (custom)';
}
}

Laravel, Singleton - how to send data to all controllers?

I'm doing shopping site. I made Cart Model, which is Singleton. My shopping cart exists in session always ( no matter or User is login or not ). Now I have to invoke every time in every Controllers and actions getInstance to check or there's key "cart".
Is there a possibility to do this automaticly for all views?
Here is code of my Singleton:
class Cart
{
private $cartModel;
private static $instance;
private function __construct()
{
$this->cartModel = new CartModel();
$cart = Session::get('cart');
if ($cart == null) {
Session::put('cart', array());
}
}
private function __clone()
{
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new Cart();
}
return self::$instance;
}
public function get(){
return Session::get('cart');
}
}
And here for example how it looks in Controllers and actions:
class StoreController extends Controller
{
public function mainSite()
{
$cart=Cart::getInstance()->get();
return View('zoo');
}
public function showCategory($categoryName)
{
$cart=Cart::getInstance()->get();
$category = new Category();
$categoryId = (int)$category->getCategoryId($categoryName);
$subCategories = Subcategory::where('category_id', $categoryId)->get();
return View('zoo-category', ['subCategories' => $subCategories, 'categoryName' => $categoryName]);
}
public function showSubcategory()
{
$cart=Cart::getInstance()->get();
}
I have to do this all the time: $cart=Cart::getInstance()->get();
Is there a possibility to do this only one time?
You can take advantage of Laravel's dependency injection. Bind your class to the IoC container and you can either access it through the IoC container or you can have Laravel automatically inject this into your controllers in several different ways.
Read more here: https://laravel.com/docs/5.4/container
Add it to base controller's constructor so that it gets called on every controller method.
// app/Http/Controllers/Controller.php
protected $cart;
public function __construct()
{
$this-> cart = Cart::getInstance()->get();
}
But i honestly see no point in your singleton class. All it does is set the cart with an empty array when it's not defined. Also $this->cartModel = new CartModel(); is this ever used?

How to get current Controller & Action in controller

How can I get current controller & action in Lumen
Let say I have a User resource in the routing.
Then if I access the user/show/id, can I get the current controller name & action name in the Controller?
class Controller extends BaseController
{
public function __construct()
{
$controllerName = ???;
$actionName = ???
}
}
Here is one simple trick to get action and controller name
class Controller extends BaseController
{
public function __construct()
{
$this->_request = app('Illuminate\Http\Request');
list($controllerName ,$actionName)=explode('#',$this->_request->route()[1]['uses']);
print_r($controllerName);
print_r($actionName);
}
}
With this you will have Action and Controller name (just name with no route):
class Controller extends BaseController
{
public function __construct()
{
list($controllerName, $actionName) = explode('#', substr(strrchr($request->route()[1]['uses'], '\\'), 1));
}
}
I have used and checked in Laravel / Lumen 8 version to get controller and action name in controller:
public function getControllerActionName(){
$this->_request = app('Illuminate\Http\Request');
list($controllerName ,$actionName) = explode('#',$this->_request->route()[1]['uses']);
$controllerName = strtolower(str_replace("App\Http\Controllers\\",'',$controllerName));
$actionName = strtolower($actionName);
return array('controller' => $controllerName, 'action' => $actionName);
}
It worked for me. I hope, this will also help you. Thanks for asking this question.

How to bind data to Model's "Display" property with MVC3?

I have a model:
public class TestModel {
[Display(Name = "Date")]
public DateTime Date { get; set; }
}
with Html.LabelFor helper method in Test.cshtml page
#Html.LabelFor(m => m.Date )
and use this page with 2 MVC action methods: Create and Update.
Example:
public virtual ViewResult Create() {
return View("Test");
}
public virtual ViewResult Update() {
return View("Test");
}
and I want to display #Html.LabelFor(m => m.Date ) with Create page: "Date" and Update page: "Update Date" . I know if the normal way of MVC3 can't do this. I hope your ideal can edit Html.LabelFor hepler method or anything way to bind data to Html.LabelFor in action methods on the controller
Adding a hiddenFor field will bind the data to your Model.
#Html.HiddenFor(m=>m.Date);
For override, please just look this answer
https://stackoverflow.com/a/5196392/5557777
you can override editorfor like this How can I override the #Html.LabelFor template? but I think you can do it more easily with ViewBag:
public virtual ViewResult Create() {
ViewBag.Title = "Create";
return View("Test");
}
public virtual ViewResult Update() {
ViewBag.Title = "Update";
return View("Test");
}
in view:
#string.format("{0} Date" , ViewBag.Title )

view return empty model asp.net mvc3

I try to initialize the DataView.Model in a partial view. The Page works fine but when I return to the controller the model is empty.
some help(solution or an explanation why it is not right).
thanks!!
code:
In my Partial View:
ViewData.Model = new DiamondPrint();
ViewData.Model.Diamond = m_db.DiamondInfoes.Where(di => di.Id == id).SingleOrDefault();
In my Controller:
public ActionResult Preview(DiamondPrint d)//the properties in d = null
{
return View(d);
}
Here is a great article on Model Binding. Model Binding Make sure you are setting the name property in your html input fields.
Looking at the code you have included it seems that you are initialising the ViewData.Model in the partial view but in the controller action you are expecting the default model binder to recreate your model. For the model binder to recreate your model you will need to have created a strongly typed view.
For example:
Controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
return View();
}
Model:
public class IndexModel
{
public string MyValue { get; set; }
}
View:
Note the #model definition at the top (ignore namespace)
#model MvcApplication14.Models.IndexModel
#using (Html.BeginForm())
{
#Html.Partial("_IndexPartial", Model)
<input type="submit" value="click"/>
}
Partial View:
#model MvcApplication14.Models.IndexModel
#Html.EditorFor(m => m.MyValue)

Resources