Server Error in '/' Application. Resource Cannot Be Found. ASP.NET MVC - c#

I'm using ASP.NET MVC 4 C Sharp and I have this error
Server Error in '/' Application.
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
Requested URL: /ClerkBooking/ConfirmBooking/22
In my controller I have:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Booking Clerk")]
public ActionResult ConfirmBooking(int id = 0)
{
if (ModelState.IsValid)
{
//Find the booking
Booking booking = db.Bookings.Find(id);
//Get RoomID of Preferred Room.
int roomId = Convert.ToInt32(db.Rooms.Find(booking.PreferredRoom));
//Set RoomID of Booking.
booking.RoomId = roomId;
//Save Changes.
db.SaveChanges();
}
return View("Index");
}
So im not sure why its not finding the method even though its in the correct place. Any help would be great! Thanks!

Your action link #Html.ActionLink("Confirm Booking", "ConfirmBooking", new {id = booking.BookingId}) is going to make a GET request, but you put an [HttpPost] attribute on the action.
You'll probably want to make the link a button inside of a form post instead of an action link.
Here's an example:
#using (Html.BeginForm("ConfirmBooking", "ClerkBooking", new { id = booking.BookingId }))
{
<input type="submit" value="Confirm Booking" />
}

Make sure your controller is called "ClerkBooking" and remove the [HttpPost] decoration from the method.

Are adding your AntiForgeryToken to your html file?
#using (Html.BeginForm("Manage", "Account")) {
#Html.AntiForgeryToken()
}
If not then probably asp.net mvc is blocking to reach your controller.
Also do not forget to check your Global.asax with the parameters:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "ClerkBooking", action = "ConfirmBooking", id = UrlParameter.Optional } // Parameter defaults
);
}
Otherwise you have to declare your id object from outside.
$.ajax("/ClerkBooking/ConfirmBooking/?id=22", {
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
//Do Something
}
}
}).fail(function () {
//Do Something
});

Related

How to pass a parameter to a controller from a cshtml view in mvc

net MVC 4 I followed the microsoft tutorials on how to pass a parameter to a controller from a cshtml view in mvc and I keep getting an error that says the resource cannot be found.If I put a break point in the cshtml I can actually see the value of the Id but it is not hitting the controller at all seems like it cant find it
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name
changed, or is temporarily unavailable. Please review the following
URL and make sure that it is spelled correctly.
Requested URL: /UploadLogs/DisplayUploadedFileContents/89
This is my controller method
public class DisplayUploadedFileController : Controller
{
private MarketingDBEntitiesModel db = new MarketingDBEntitiesModel();
// GET: DisplayUploadedFile
public ActionResult DisplayUploadedFileContents(int UploadId)
{
return View(db.marketingdbclients_dataTable.OrderByDescending(r => r.ClientId).Where(r => r.ClientDataId < 1000).ToList());
// return View();.
}
}
My line in the cshtml
<td>
#*#Html.ActionLink("Details", "Details", new { id = item.UploadId })*#
#Html.ActionLink("Details", "DisplayUploadedFileContents", new { id = item.UploadId })
</td>
My route config
routes.MapRoute(
name: "DisplayUploadedFileContents",
//url: "",
url: "{controller}/{action}/{id}",
defaults: new { controller = "DisplayUploadedFile", action = "DisplayUploadedFileContents", id = UrlParameter.Optional });
Making a couple of changes should get this working.
First, if you want to use the routing for the url like this {controller}/{action}/{id}, change the parameter name in the controller action from UploadId to id:
public ActionResult DisplayUploadedFileContents(int id)
Next, it looks like you're linking from a different controller since in the error the requested URL is /UploadLogs/DisplayUploadedFileContents/89 (note UploadLogs is not DisplayUploadedFile).
Linking to the DisplayUploadedFile controller from a view that belongs to a different controller, you will need to use this overload taking 5 parameters:
#Html.ActionLink("Display File Contents", "DisplayUploadedFileContents", "DisplayUploadedFile",
null, new { id = item.UploadId })
However, if you're accessing the controller from a view within the same controller you should be able to use this overload for ActionLink taking 3 parameters:
#Html.ActionLink("Display File Contents", "DisplayUploadedFileContents", new { id = item.UploadId })
Please refer to the ActionLink documentation
url: "{controller}/{action}/{id}
You didn't respect the routing configuration. Try:
#Html.ActionLink("DisplayUploadedFile", "DisplayUploadedFileContents", new { UploadId = item.UploadId })
#Html.ActionLink("DisplayUploadedFile", "DisplayUploadedFileContents", new { UploadId = item.UploadId}, null )
You need the Argument for "htmlArgument"
Please Refer to: HTML.ActionLink method

HttpPost won't be called

I have been at this for an hour now and I haven't got a clue what I am doing wrong.
I got the following ActionLink:
#Html.ActionLink("Remove", "RemoveActivity", "Dashboard", new { id = a.Id },htmlAttributes: null)
This targets the following Method in my DashboardController:
[HttpPost]
public ActionResult RemoveActivity(int id)
{
activityRepo.Delete(activityRepo.GetById(id));
return RedirectToAction("ActivityDetails");
}
For some reason this error gets returned:
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
Requested URL: /Dashboard/RemoveActivity/564
A table row with the Id of 564 does exist in the database. It worked a few hours ago.
Any help is appreciated. I am clueless!
EDIT:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HaarlemFestival_Web
{
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 }
);
}
}
}
#Html.ActionLink() generates a <a> tag which makes a GET, not a POST. You need to include a <form> element and submit the value to your POST method
#using (Html.BeginForm("RemoveActivity", "Dashboard", new { id = a.Id }))
{
<input type="submit value="Remove" />
}
and you can style your submit button to look like a link if that is what you want visually
I also suggest you add the #Html.AntiForgeryToken() method in the <form> and add the [ValidateAntiForgeryToken] attribute to your method to prevent CSRF attacks.
You should also consider validating that the current user does have the permission to delete that record.
Note that since you method is changing data, it should be a POST, so do not be tempted to just remove the [HttpPost] attribte from your method so that the link works.
Because #Html.ActionLink will render an anchor tag, Clicking on which is always "GET" request. So if you want an HTTP-Post method you need to override its behavior using javascript like this:
#Html.ActionLink("Remove", "RemoveActivity", "Dashboard", new { id = a.Id ,#class="post_link"},htmlAttributes: null);
[HttpPost]
public String RemoveActivity(int id)
{
activityRepo.Delete(activityRepo.GetById(id));
return "Remove/ActivityDetails";
}
<script type="text/javascript">
$(function(){
$("a.post_link").click(function(e){
e.preventDefault();
$.post($(this).attr("href"),function(data){
//got your redirection link and do a redirection request at here
window.location = data;
});
});
});
</script>
You can try this , very simple way
In you view just place anchor tag: // make sure you have Id coming here
Remove
Jquery block:
<script type="text/javascript">
function RemoveActivity(index) {
var urlBase = '/Dashboard/RemoveActivity/';
$.ajax({
url: urlBase,
data: { id: index },
success: function (result) {
},
error: function (ex) {
}
});
}
</script>
keep your controller action as post method only. I hope this helps.

Why aren't my links taking me into my controller?

I guess I don't completely understand how urls work with C# projects, in the sense that I don't know how to specify a url to go through the controller and not just return a aspx page.
Say I am trying to get to my project's Index page through a Controller named "ScholarshipController.cs". I would think to hit the Index method/action in this controller, my url would be as follows (my app's name is "TuitionAssistance" fyi):
http://localhost/TuitionAssistance/Scholarship/Index
However, running this url just returns the aspx page named "Index.aspx" located in the "Scholarship" view file without hitting the Controller. Why is this happening, and how do I get it to go through the controller so the Index page, when loaded, will have the appropriate information loaded onto it?
Sorry if this is a dumb question. Any insight would be appreciated. Thanks!
Route.config:
using System.Web.Mvc;
using System.Web.Routing;
namespace ScholarshipTuitionAssistance
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
/* Scholarship */
/* Scholarship */
//routes.MapRoute("TuitionAssistance",
// "tuition/{name}",
// new { controller = "TuitionAssistance", action = "Index", name = "" });
routes.MapRoute(
name: "TuitionAssistance",
url: "{controller}/{action}/{employee_number}",
defaults: new { controller = "Home", action = "TuitionAssistance", employee_number = UrlParameter.Optional }
);
routes.MapRoute(
name: "Scholarship",
url: "{controller}/{action}/{employee_number}",
defaults: new { controller = "Home", action = "Scholarship", employee_number = UrlParameter.Optional }
);
routes.MapRoute(
name: "Details",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Scholarship", action = "Details", id = UrlParameter.Optional }
);
}
}
}
Your route (URL) cannot match anything that actually exists on the filesystem. In your example here, you apparently have a file, [document root]\Scholarship\Index.aspx. As a result, a request for Scholarship/Index will return that file, instead of invoking the ASP.NET MVC machinery to load a controller action.
In MVC ASP.NET, think of those types of links as a way to call your methods in your controller. When that link is accessed, your controller does a bunch of junk and then returns an ActionResult (or other things). This ActionResult, for the sake of this explanation, is the markup that is written in the corresponding view file. Controller - >index() will return the view called index under views - > controller. If you want to pass information to your view, you will pass a model that has all of your information in it to the view from your index controller (return View(MyFancyModel)). The view will have a razor line at the top such as: #model The.Namespace.Wherever.my.model.is
The scaffolded controllers and views in Visual Studio for the index page specifically, only pass a list of the items in the corresponding database.

Controller Method Using Custom Parameter Name

I am having a problem when I use custom parameter name instead of id in my method in asp.net MVC controller.
My working method is:
// POST: Admin/Pages/ReorderPages
[HttpPost]
public void ReorderPages(int[] id)
{
using (Db db = new Db())
{
//Set Initial count
int count = 1;
//Declare PageDTO
PageDTO dto;
//Set sorting for each page
foreach (var pageId in id)
{
dto = db.Pages.Find(pageId);
dto.Sorting = count;
db.SaveChanges();
count++;
}
}
}
my ajax call is:
$("table#pages tbody").sortable({
items: "tr:not(.home)",
placeholder: "ui-state-highlight",
update: function () {
var pageids = $("table#pages tbody").sortable("serialize");
var url = "/Admin/Pages/ReorderPages";
$.post(url, pageids, function (data) {
});
}
});
Now, when I use different param instead of id, I get null value in param. I added new route also like below: But still, the problem is same.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name:"CustomRoute",
url:"{controller}/{action}/{ids}",
defaults:new { controller = "Pages", action = "ReorderPages" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I spent pretty much time in research but couldn't find the exact solution.
Why don't you use
var pageids = $("table#pages tbody").sortable("serialize");
$.ajax({
url: "/Admin/Pages/ReorderPages",
data: { id: pageids }
})
.done(function(response) {
alert("works");
});
.fail(function(response){
alert("failed because of..");
}
Look into Ajax calls and promises. It works really nice and this way no need to play around with routing. If this still not passing through the ids then you debug through your code, but in that case your problem is with the var pageids = var pageids = $("table#pages tbody").sortable("serialize"); line
If you really want to stick with your way of doing it. Use this
$.post(url, { newParameter : pageids }, function (data)
After this you can rename your parameter inside the ActionMethod
public void ReorderPages(int[] newParameter)

ASP.NET MVC - Get parameter value from URL in the view

How do I get parameter value from the URL in the client side, view?
URL:
localhost:18652/category/1
MapRoute:
routes.MapRoute(
name: "ResultsByCategory",
url: "category/{id}",
defaults: new { controller = "Home", action = "ResultsByCategory"}
);
How do I get ID?
I tested this url:
http://localhost:1865/category/Index/1
In view I have this:
You can get id by this code in example view:
#{
var id = Request.Url.Segments[3];
}
In general case, You can use this code:
#{
var id = Request.Url.Segments.Last();
}
Didn't understand the point of directly getting from URL, Request as your view is always going to get loaded from your controller.
So as derloopkat suggested
In your Home Controller
Public ActionResult ResultsByCategory (int id)
{
ViewBag.id = id;
return View();
}
In your view you can use it by calling
#ViewBag.id
This code works better for your code
string id = Request.Path.Value.Split('/').LastOrDefault();

Categories

Resources