I have several roles for users in my website.
I need to return different view on user role.
Now I have call View default way
public ActionResult Index()
{
return View();
}
But I need this: if user has Admin role I return Index.cshtml.
If it has user role I need to return IndexUser.cshtml.
How I can realize it?
UPDATE
I tried to realize it like this
public ActionResult Index()
{
if (User.IsInRole("Admin"))
{
return View();
}
if (User.IsInRole("Test"))
{
return View("IndexProjectManager");
}
return View();
}
But it always going to return View
if you want to do itin view then you can use below to redirect to another view:
return RedirectToAction("Reporting", "ReportManagement", new { area="Admin" })
I mean on the basis of condition as below:
if (isAdmin)
{
return view();//supposing it is the view for admin
}
else
{
return RedirectToAction("Reporting", "ReportManagement", new { area="Admin" })
}
if (User.IsInRole("admin")) //whatever your admin role is called
{
return View();
}
if (User.IsInRole("user"))
{
return View("IndexUser");
}
return View("Whatever"); //or RedirectToAction(...)
Note: I'm basing this on assuming how your Roles work...apologies if this isn't quite appropriate.
You could make it so that Index View is the lowest level (basic) user view then have suffixes appended to each 'higher' role's views.
That way, you could do something like this:
[Authorize] //make sure they're logged in
public ActionResult Index()
{
string _viewSuffix = "";
//this bit would have to be hierarchical - high to low - so you have a degradation of what the view offers...
if (User.IsInRole("Admin"))
{
_viewSuffix = "Admin";
}
else if(User.IsInRole("Test"))
{
_viewSuffix = "Test";
}
//...and so on
return View("Index" + _viewSuffix);
}
Related
this is the controller
public ActionResult Test() {
#ViewBag.TheMessageIs = "this is the message";
return RedirectToAction("Details", new { id = theId});
}
on the view of Action Named Details I will check if it has the ViewBag to show and show it:
#{
if(ViewBag.TheMessageIs != null){
#ViewBag.TheMessageIs
}
}
but here the redirection is working fine to the page, it's not show the message I have stored in ViewBag.TheMessageIs
thanks
Basically what you're doing is invoking the method Details from your Index method and since you're already overloading your Details action with an id, pass it the message as well:
public ActionResult Index()
{
//ViewBag.TheMessageIs = "this is the message";
return RedirectToAction("Details", new { id = 1, TheMessageIs = "this is the message" });
}
public ActionResult Details(int id, string TheMessageIs)
{
ViewBag.TheMessageIs = TheMessageIs;
return View();
}
Then in the Details view you can access the property like this:
#ViewBag.TheMessageIs
public ActionResult Test() {
TempData["shortMessage"] = "MyMessage";
return RedirectToAction("Details", new { id = theId});
}
public ActionResult Details {
//now I can populate my ViewBag (if I want to) with the TempData["shortMessage"] content
ViewBag.TheMessageIs = TempData["shortMessage"].ToString();
return View();
}
You have to do it like this since the viewbag looses its value when you redirect to another active / view
Can anyone please help me? I am trying to call a view which is present in Home Controller directly from the action method of another controller. I don't want to use the return redirectToAction() method, but rather would like to call the view of HomeController directly. In HomeController I have this HttpGet Method:
public ActionResult SuperAdmin()
{
if (Session["User"] != null)
{
TempData["BindGrid"] = objDBContext.tbl_Student.Where(X => X.RegistrationConfirmed == false).ToList();
return View(); //Go to SuperAdmin View if condition is true
}
else
{
return View("Login", "Home"); //else redirect to Login view
}
}
Present Controller from where i would like to call HomeController SuperAdmin View
public ActionResult Search(string Search)
{
if (Session["User"] != null)
{
if (Search != string.Empty)
{
TempData["BindGrid"] = objDBContext.tbl_Student.Where(X => (X.UserName.StartsWith(Search) || Search == null) && (X.RegistrationConfirmed == false));
}
return View("SuperAdmin", "Home"); //If true, go to SuperAdmin view directly
}
else
{
return RedirectToAction("Login", "Home");
}
}
You can directly return a different view like:
return View("yourViewName", Model); //if it is in same controller and if you pass model then pass model in this way
if your view is in different controller then
return View("FolderName/ViewName", Model ); // pass a view of a different controller with model. Just specify view name and it's folder name
I have a controller method that is returning the wrong view. The view I have is the same name as the controller method "AssignTask.cshtml". The method is "public virtual ActionResult AssignTask(ManageTaskModel model) "
Can anyone see what I'm doing wrong?
[HttpGet]
public virtual ActionResult ManageTasks()
{
try
{
var model = new ManageTaskModel ();
model.assignedPSUsers = Orchestrator.GetAssignedPSUsers();
return View(model);
}
catch (Exception e)
{
ModelState.AddModelError("ErrorMsg", e.Message);
};
return this.RedirectToAction("Index");
}
[HttpPost]
public virtual ActionResult ManageTasks(ManageTaskModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
try
{ //User has seleced the user that they want to see Tasks for
if (model.selectedUser != null && model.newUser==null)
{
model.assignedPSUsers = Orchestrator.GetAssignedPSUsers();
model.FcvsTaskList = Orchestrator.GetTasksForAssignedPSUser(model.selectedUser);
return AssignTask(model);
}
}
catch (Exception e)
{
ModelState.AddModelError("ErrorMsg", e.Message);
return View(model);
}
return this.RedirectToAction("Index");
}
[HttpGet]
public virtual ActionResult AssignTask(ManageTaskModel model)
{
if (model.selectedUser != null && model.newUser == null)
{
**return View(model);** //returning the ManageTask instead of AssignTask View
}
return this.RedirectToAction("Index");
}
In your ManageTasks action you return AssignTask(model). This doesn't work, because the request context still remembers that the user actually called ManageTasks. That's why it returns the view for ManageTasks.
The right way to do it is like that:
return RedirectToAction("AssignTask", model); // remember to pass the model here
You can see that if you put this line in AssignTask:
HttpContext.Request.Path
If you access it from ManageTasks using return AssignTask(model), the value will be "/YourController/ManageTasks".
If you either call this action directly from browser or with RedirectToAction the value will be "/YourController/AssignTask".
you can't redirect that way. instead of return AssignTask you need
return RedirectToAction("AssignTask");
and pass an id or something there. you will need to recreate the model in your AssignTask method
I'm to new asp.net and asp.net MVC. I'm trying to show a user a page depending on the role his in.
public class HomeController : Controller
{
[Authorize(Roles = "Reviewer")]
public ActionResult Index()
{
ViewBag.Title = "Reviwer";
return View();
}
[Authorize(Roles="User")]
public ActionResult Index()
{
return View();
}
}
My code is the one above, it makes perfect sense that it won't compile like this i can't cave two idendical methods with the same name. But can someone please point me in the right direction. How am i supposed to show the user o different page based on his role.
If they must be two separate actions, then it makes more sense to name them according to role, like so:
public class HomeController : Controller
{
[Authorize(Roles = "Reviewer")]
public ActionResult Reviewer()
{
ViewBag.Title = "Reviewer";
return View();
}
[Authorize(Roles="User")]
public ActionResult User()
{
return View();
}
}
If you can have them as one, you could do:
public class HomeController : Controller
{
[Authorize(Roles = "Reviewer", "User")]
public ActionResult Index()
{
if (User.IsInRole("Reviewer"))
{
return View("Reviewer");
}
else
{
return View("User");
}
}
}
Are there different views for each role or is it just that you want to have a different title depending on their role?
What you could do is combine the roles into a single Controller method and then inside the method have conditional logic, as a naive example:
public class HomeController : Controller
{
[Authorize(Roles = "Reviewer, User")]
public ActionResult Index()
{
if (Roles.IsUserInRole("Reviewer"))
{
ViewBag.Title = "Reviwer";
}
return View();
}
}
If all you were doing was changing the title. If you wanted to display a different view or redirect them somewhere else you could do:
[Authorize(Roles = "Reviewer, User")]
public ActionResult Index()
{
if (Roles.IsUserInRole("Reviewer"))
{
return View("ReviewerView");
}
else if (Roles.IsUserInRole("User"))
{
//Or do a RedirectToAction("SomeAction")
return View("UserView");
}
}
Do a test in the action whether the user is in a role and return a different view or redirect to a different action.
You could try something like:
public class HomeController : Controller
{
[Authorize(Roles = "Reviewer,User")]
public ActionResult Index()
{
if (User.IsInRole("Reviewer")){
ViewBag.Title = "Reviwer";
return View("IndexReviwer");
}
return View();
}
}
Need to create a View called IndexReviwer
My page has a search box which for has a few radio buttons. Depending on which radio button is selected will depend on which view is shown.
However, I don't know how to return the View.
My code is
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
CandidateResults();
else
JobResults();
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}
But this displays nothing on screen (a white page). This makes sense but I don't want to return Index, I want to return a new page (called either JobResults or Candidates) and create a View for both of these new pages but when I right click in my methods (JobResults() or Candidates()) I don't get the option to Add View.
At this stage I'm lost, can any one please give advice.
Either return the view from Index or redirect to CandidateResults or JobResults actions.
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
return CandidateResults();
else
return JobResults();
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}
Try this
public ActionResult Index(string jobType)
{
return (jobType.ToLower() == "this") ?
RedirectToAction("CandidateResults") :
RedirectToAction("JobResults");
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}
In your private methods you have to specify the actual view you want to display.
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
CandidateResults();
else
JobResults();
}
private ActionResult CandidateResults()
{
var model = //logic
return View("CandidateResults", model);
}
private ActionResult JobResults()
{
var model = //logic
return View("JobResults", model);
}
This happens because of the way the view engine works. The action name for the current request is always Index when the index function is called. Even if you call another method, the view engine will use the name of the current action and not the name of the currently executing function.
Just you need to redirect the user to proper controller method and that method will return its View as below:
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
return RedirectToAction("CandidateResults","ControllerName");
else
return RedirectToAction("JobResults","ControllerName");
}
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
return RedirectToAction("CandidateResults");
return RedirectToAction("JobResults");
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}