I have a basic controller:
using System.Web Mvc;
namespace MainProject.Controllers
{
public class Main : Controllers
{
public ActionResult Index()
{
return View();
}
}
}
with a view:
View/
Main/
Index.cshtml
And yet it doesn't return the page, it just the resource cannot be found. What am I missing here?
localhost:60555/Main/Index
try the below changed code it will surely work for you
your code:
using System.Web Mvc;
namespace MainProject.Controllers
{
public class Main : Controllers
{
public ActionResult Index()
{
return View();
}
}
}
Changed code :
using System.Web Mvc;
namespace MainProject.Controllers
{
public class MainController : Controller
{
public ActionResult Index()
{
return View();
}
}
Hope it was helpful
Thanks
Karthik
Related
This is my roles under homecontroller file there are 3 user as below how do i add functionality to manager so he can view /edit or delete
what all files ill need to edit i tried youtube and stuff but didnt find a clear picture
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CustomRoleProvider.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[Authorize(Roles="User")]
public ActionResult UserArea()
{
return View();
}
[Authorize(Roles ="Admin")]
public ActionResult AdminArea()
{
return View();
}
[Authorize(Roles = "Manager")]
public ActionResult ManagerArea()
{
return View();
}
}
}
I've found many topic and suggestions on this and I think I've tried all of the combinations.
I had a working application that is going to grow larger so I decided to make use of areas. I sloughed through that and can access the controllers but then the application fails when it tries to return data to a view. I created a test data context, classes, etc. then to be sure that it wasn't something that I did wrong when moving into areas.
It's probably best to work through the somewhat smaller test situation and then apply what works to the larger actual application.
My link from _Layout.cshtml:
<li>#Html.ActionLink("Test", "Index", "testclasses")</li>
My model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tracking.Areas.test.Models
{
public class testclass
{
public int ID { get; set; }
}
}
My testAreaRegistration:
using System.Web.Mvc;
namespace Tracking.Areas.test
{
public class testAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "test";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"test_default",
//"test/{controller}/{action}/{id}",
"test/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
My test controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tracking.Areas.test.Models;
using Tracking.DAL.Test;
namespace Tracking.Areas.test.Controllers
{
[RouteArea("test")]
public class testclassesController : Controller
{
private testcontext db = new testcontext();
// GET: test/testclasses
public async Task<ActionResult> Index()
{
return View(await db.spas.ToListAsync());
}
// GET: test/testclasses/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
testclass testclass = await db.spas.FindAsync(id);
if (testclass == null)
{
return HttpNotFound();
}
return View(testclass);
}
// GET: test/testclasses/Create
public ActionResult Create()
{
return View();
}
// POST: test/testclasses/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ID")] testclass testclass)
{
if (ModelState.IsValid)
{
db.spas.Add(testclass);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(testclass);
}
// GET: test/testclasses/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
testclass testclass = await db.spas.FindAsync(id);
if (testclass == null)
{
return HttpNotFound();
}
return View(testclass);
}
// POST: test/testclasses/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID")] testclass testclass)
{
if (ModelState.IsValid)
{
db.Entry(testclass).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(testclass);
}
// GET: test/testclasses/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
testclass testclass = await db.spas.FindAsync(id);
if (testclass == null)
{
return HttpNotFound();
}
return View(testclass);
}
// POST: test/testclasses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
testclass testclass = await db.spas.FindAsync(id);
db.spas.Remove(testclass);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My RouteConfig file
namespace Tracking
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
My Global.asax.cs file
namespace Tracking
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
I've tried with and without [RouteArea("test")] in the controller; I've tried multiple options with adding a controller to the area registration file, removing the area name from in front of controller in the area registration file, and many other combinations.
The code finds the controller and model as I put breakpoints in those and reach them - when it attempts to return the view I get the error message about the index view not being found in the standard locations - it doesn't search within the areas at all.
Thanks!
I think you have an inconsistence in your "convention over configuration" setup. Might be helpful to add the error message and your solution structure. You should check, for example, that the Index.cshtml is found in the Areas\test\Views\testclasses folder. The only thing that I see at a first glance is that you didn't modify your action link to include the area. You should try:
#Html.ActionLink("Test", "Index", "testclasses", new { Area = "test" }, new{})
P.S.> I would recommend using camel case notation for the class names and areas... you know, for the clean code sake. Not to mention that you never know when you might stumble upon a case sensitive convention....
I would like to return an Action to an other Controller
Example: i have 2 controlers:
[Route("myurl"]
public class HomeController : Controller
{
public ActionResult Action1()
{
if (...)
{
return Action2(); //working fine i will keep my route
}
else
{
return OtherController.Action3(); //Don't know how to do it here.
}
}
public ActionResult Action2()
{
return View();
}
}
and
public class OtherController : Controller
{
public ActionResult Action3()
{
return View();
}
}
It's working if the Action is inside the same controller but wish to return the Action1 from HomeController to Action3 from OtherController.
I want to keep the same route (not a redirection to an other route).
Any idea ?
Have you tried using this RedirectToAction?
return RedirectToAction("ACTION_NAME", "CONTROLLER_NAME", new { area = "" });
I found out:
I need to return like that :
return DependencyResolver.Current.GetService<OtherController>().Action3();
[Route("myurl"]
public class HomeController : Controller
{
public ActionResult Action1()
{
if (...)
{
return Action2(); //working fine i will keep my route
}
else
{
return DependencyResolver.Current.GetService<OtherController>().Action3();
}
}
public ActionResult Action2()
{
return View();
}
}
return RedirectToAction("ActionName", "ControllerName");
You can do this by calling the below method of controller class protected internal RedirectToRouteResult RedirectToAction(string actionName, string controllerName); For your requirement the code inside the else block would look like base.RedirectToAction("ACtion3","OtherController");
In my project I have two different controllers.
This is the main one:
public class Main : Controller
{
public ActionResult Index()
{
return View();
}
}
And this is the other one:
public class OtherOne : Controller
{
public ActionResult RandomAction()
{
return ... //more code here
}
}
What should I return in "OtherOne/RandomAction" in order to obtain the same result of "Main/Index" action?
It's as simple as this:
public class OtherOneController : Controller
{
public ActionResult RandomAction()
{
return RedirectToAction("Index", "Main");
}
}
Your Controller class names must be MainController and OtherOneController. If you want to change that, check this post:
change controller name convention in ASP.NET MVC
Here is your Main Controller:
public class MainController : Controller
{
public ActionResult Index()
{
return View();
}
}
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