A public action method was not found on controller - c#

I am working on a project on asp.net MVC3, I have a controller named UserProfile when i run my project and login, it shows error A public action method images was not found on controller UserProfile
I don't have any action method named images in any of my controllers,below is my UserProfile's index method
[CustomAuthorizeAttribute]
public ActionResult Index()
{
var userName = string.Empty;
if (SessionHelper.GetSession("login") != null)
{ userName = SessionHelper.GetSession("login").ToString(); }
else
{ return View(); }
SessionHelper.SetSess("issetup", null);
UserProfileModel model = GetUserProfileData(userName);
StateandCityDropdown();
return View(model);
}
I have two forms on userprofile index view one with some textboxes and other fields for entering data and second for uploading images

It sounds to me like the routes are picking up on a url you have and mistaking them for an action. It could be that you have a link to an image directory underneath a directory that matches your controller such as /User/Images would thow this error because the routing would then expect you to have an Images action when you dont. Check the page source for anything linking to an images folder but without an image included. The other option is that the routes are picking up the images as well as the actions you want them to. If this is the case in your Global.asax.cs file check the RegisterRoutes method has some ignores in for images.
routes.Ignore("{*allpng}", new { allpng = #".*\.png(/.*)?" });
routes.Ignore("{*allgif}", new { allgif = #".*\.gif(/.*)?" });
routes.Ignore("{*alljpg}", new { alljpg = #".*\.jpg(/.*)?" });
Hope this helps
Andy

Related

Net Fiddle problema with route

i'm problem with Net Fiddle use MVC. When i click the button "Ordernar por Nome" result in Erro page, but in my PC works well.
https://dotnetfiddle.net/HCLpdv
The problem code is:
[HttpGet]
public ActionResult Index()
{
listPessoas = new List<Pessoa>();
populatePessoas(listPessoas);
CountSituacao();
ViewData["pessoas"] = listPessoas;
return View();
}
[HttpGet]
public ActionResult OrderByName()
{
OrderList();
ViewData["pessoas"] = listPessoas;
return View("Index");
}
My problem is that when Net Fiddle executes OrderByName action it says that it can't find view
Thanks!
I would say that this is a specific of Net Fiddle as we don't have actual file system there and it has only one view. And UI doesn't allow to specify name for that view.
We treat view name dynamically based on current action name. In your case you have two actions Index and OrderByName, so if both methods will use default View() without specifying viewName, then it will be working fine as by default we render view based on current executing action.
It's not so correct behavior, but otherwise we need ability to specify a couple of views with names, that we can't do right now.
So to fix your issue you just need to use such action code:
[HttpGet]
public ActionResult OrderByName()
{
OrderList();
ViewData["pessoas"] = listPessoas;
return View("OrderByName");
}
Or just empty View()

MVC Wild Card route mapping not working on documents

I have a page in my MVC site that is used to browse through a folder structure on the server, but the wild card mapping is not working for documents.
The mapping works for folder names such as
http://localhost:4321/Document/Folder/General_HR
Which maps to a shared drive folder like T:\root\General_HR in the controller.
But I get a 404 and the controller method isn't hit when trying to access a file such as
http://localhost:4321/Document/Folder/General_HR/Fire_Drill_Procedures.doc
Here is the route mapping
routes.MapRoute("Document Folder",
"Document/Folder/{*folderPath}",
new { controller = "Document", action = "Folder" });
I also have the standard MVC route that is applied after the one above:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I tried commenting out all other routes, but it still doesn't work.
I had had it working at one point, but I don't know what has changed since then. It seems that it's looking for a resource located at C:\MyProject\General_HR instead of being routed to the controller. How can I fix my mapping to account for this? According to this answer it should be working.
My controller method works like this: if the URL parameters contains an extension, then I return File(filePath), otherwise I create a view model and return View(viewModel). So when I click on something with an extension, it should still point to this same controller method and return the file.
public virtual ActionResult Folder(string folderPath)
{
var actualFolderPath = folderPath;
if (string.IsNullOrEmpty(actualFolderPath))
{
actualFolderPath = DocumentPathHelper.RootFolder;
}
else
{
actualFolderPath = DocumentPathHelper.GetActualFileLocation(actualFolderPath);
}
if (System.IO.File.Exists(actualFolderPath))
{
return File(actualFolderPath, MimeMapping.GetMimeMapping(actualFolderPath));
}
var vm = new FolderViewModel();
//build vm
return View(vm);
}
I "solved" this by altering my urls to the documents by replacing the . with a placeholder, then replacing it back in the controller.
for each item:
folderPath = folderPath.Replace(".", "___");
Then in the controller:
public virtual ActionResult Folder(string folderPath)
{
var actualFolderPath = folderPath.Replace("___", ".");

How Can I Pass a 404 Error from Model in MVC 4 to View

In my RouteConfig.cs file I have the following to handle my Url requests;
routes.MapRoute("Product", "products/{Url}",
new { controller = "product", action = "index" });
In my model, I check that the Url entered exists in my database. However, I want to return a 404 error that the requested page does not exist, if I can't find a match in my database.
How can I achieve this ?
In the controller's method, you can return a HTTP response like this :
if (product == null)
{
return HttpNotFound();
}
Hope it helps !

Nested Folders in MVC3 Visual Studio 2010

I'm a web developer new to using the MVC3 framework. We're building a site that implements a lot of sub folders for different segments of our audience. This routing concept is throwing a wrench in our structure for SEO.
In my global.asax file under the routing section we have:
routes.MapRoute("test", "test/{testFirst}/{testSecond}",
new { controller = "test", action = "RouteTest", testSecond = UrlParameter.Optional });
and in my controller we have:
public ActionResult RouteTest(string testFirst, string testSecond)
{
return View(testFirst, testSecond);
}
When I run the site and try to go to /test/test/index it won't pull up the view. It's stuck looking for test.cshtml which doesn't exist because it's a folder not a file.
Any ideas on to how make nested folders work?
EDIT:
Here's a branch of the structure we want and maybe it will help with what I'm trying to accomplish.
This is kind of hard to show but it should get the idea across. We have 5 different audiences that come to the site. I broke down 1 audience and what the flow of that audience is.
Not all segments will have products some are just content other segments have that 3rd level and have products to view
audience
segment
segment
products
segment
products
segment
This is the basic structure that we want the URLs to take
domain.com/audience/segment/products/(productsname)
Suggestions on how to make this possible
You are using the wrong overload for the View() method. Here's what you're using when you call View(testFirst, testSecond):
protected internal ViewResult View(
string viewName,
string masterName
)
MSDN Reference.
By putting "test" for the viewName, you're telling the Controller to render a View called Test (test.cshtml). Which you don't have.
It sounds to me like you are trying to correlate WebForms with MVC. It is not the same, and you are seeing a prime example with routing. ASP.NET MVC doesn't work off of the NTFS structure (folders and files). It relies on routing through route definitions.
If you are looking to render the View "RouteTest", then do something like this:
public ActionResult RouteTest(string testFirst, string testSecond)
{
ViewBag.testFirst = testFirst;
ViewBag.testSecond = testSecond;
return View();
}
This will render the "RouteTest" view and in your dynamic object ViewBag you will have access to two properties: testFirst and testSecond. In your view you can pull those values. (Although I highly recommend strongly-typed Views using a ViewModel)
Example Solution
ViewModel
public class TestData
{
public string testFirst { get ; set ; }
public string testSecond { get ; set ; }
}
Controller
public ActionResult RouteTest(string testFirst, string testSecond)
{
TestData td = new TestData();
td.testFirst = testFirst;
td.testSecond = testSecond;
return View(td);
}
Strongly-Typed View
#model TestData
#Html.Label(Model.testFirst)
#Html.Label(Model.testSecond)

ASP MVC Redirect without changing URL(routing)

Goal:
I want to be able to type URL: www.mysite.com/NewYork OR www.mysite.com/name-of-business
Depending on the string I want to route to different actions without changing the URL.
So far I have:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"UrlRouter", // Route name
"{query}", // URL with parameters
new { controller = "Routing", action = "TestRouting" } // Parameter defaults
);
}
In the controller I have:
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
return RedirectToAction("Index", "Availability"); // <--------- not sure
else if (query == "name-of-business")
return Redirect("nameofbusines.aspx?id=2731"); // <--------- not sure
else
return RedirectToAction("TestTabs", "Test"); // <--------- not sure
}
I have pretty much tried everything to redirect/transfer to the page without
changing the URL, but everything I've tried changes the URL or gives me an error.
Basically I'm looking for the equivalent of server.transfer where I can keep the URL but send info to the action and have it display its result.
I'm with Nick on this one, though I think you could just use regular views instead of having to do partials. You may need to implement them as shared views if they are not in the views corresponding to the controller (since it will only look in the associated and shared views).
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
{
var model = ...somehow get "New York" model
return View("Index", model );
}
else if (query == "name-of-business")
{
var model = ...get "nameofbusiness" model
return View("Details", model );
}
else
{
return View("TestTabs");
}
}
Each view would then take a particular instance of the model and render it's contents using the model. The URL will not change.
Anytime that you use a RedirectResult, you will actually be sending an HTTP redirect to the browser and that will force a URL change.
Im not sure if you tried this way or if this way has any drawbacks..
Add a global.asax file to your project. In that add the following method:
void Application_BeginRequest(object sender, EventArgs e)
{
// Handles all incoming requests
string strURLrequested = Context.Request.Url.ToString();
GetURLToRedirect objUrlToRedirect = new GetURLToRedirect(strURLrequested);
Context.RewritePath(objUrlToRedirect.RedirectURL);
}
GetURLToRedirect can be a class that has the logic to find the actual URL based on the URL typed in. The [RedirectURL] property will be set with the url to redirect to beneath the sheets.
Hope that helps...
You can change your controller like this:
public ActionResult TestRouting(string query)
{
string controller,action;
if (query == "NewYork")
{
controller = "Availability";
action = "Index";
}
else
{
controller = "Test";
action = "TestTabs";
}
ViewBag.controller = controller;
ViewBag.action = action;
return View();
}
Then you can use these ViewBags in your view like this:
#{
Layout = null;
Html.RenderAction(ViewBag.action, ViewBag.controller);
}
That's it. And you can improve this example with use a class and some functions.
Are you saying you want to go to "www.mysite.com/NewYork" and then "really" go "somewhere else" but leave the url alone? Perhaps what you would want to do then is use partial views to implement this? That way, your base page would be what gets routed to, and then inside of that page you do your condition testing to bring up different partial views? I've done that in my application for viewing either a read-only version of a grid or an editable grid. It worked very nicely.
I'm not sure what you can do about the redirect to the .aspx page, but you should be able to replace the RedirectToAction(...)s with something like this:
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
{
var controller = new AvailabilityController();
return controller.Index();
}
else if (query == "name-of-business")
return Redirect("nameofbusines.aspx?id=2731"); <--------- not sure
else
{
var controller = new TestController();
return controller.TestTabs();
}
}

Categories

Resources