Edit View in asp.net mvc - controller error - c#

I'm writing web service in asp.net mvc and still having the same error connected with the code below:
public ActionResult Edit(int C)
{
var customers = _ourCustomerRespository.GetCustomers();
var std = customers.Where(s => s.CustomerID == C).FirstOrDefault();
return View(std);
}
[System.Web.Http.HttpPost]
public ActionResult Edit(Customer C)
{
return RedirectToAction("Index");
}
and when i try use my service i have error message
The current request for action 'Edit' on controller type
'DefaultController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Edit(Int32) on type
WebApplication2.Controllers.DefaultController
System.Web.Mvc.ActionResult Edit(WebApplication2.Models.Customer) on
type WebApplication2.Controllers.DefaultController
Can anybody help me with solving that?

That's because you decorated your controller action with the wrong HttpPost attribute. You need this one:
[System.Web.Mvc.HttpPost]
public ActionResult Edit(Customer C)
The one you have used (System.Web.Http.HttpPost) is designed for ASP.NET Web API actions and has strictly zero effect when placed on an ASP.NET MVC controller action. So the ASP.NET MVC framework cannot disambiguate between the 2 Edit actions because they are using the same verb and thus you are getting the error.
Remark: please make sure that you tag your question correctly to avoid any confusions. Currently you have used the asp.net-web-api whereas the controller action you have shown is clearly asp.net-mvc. Those are 2 completely different frameworks.

Related

Url.Action routes to the wrong controller

I have two controllers, one Web API controller and the other a MVC controller. These two controllers have the same name and the same action name, though the one in API controller is a post while the one in MVC is a get, as shown here.
This is the API controller:
[Route("api/[controller]")]
public class SameNameController : ControllerBase
{
[HttpPost]
public IEnumerable<*className*> SameNameAction([FromBody] *typeName*[] data)
{
// Detail implementation
}
}
And this is the MVC controller:
public class SameNameController: Controller
{
public ActionResult SameNameAction(int? page, int? pageSize)
{
//Detail implementation
}
}
I'm using X.PagedList to generate pagination. When I click any of pages, I receive an error
HTTP 405 - this page isn't working
Upon further inspection, I realized that the URL generated is the issue.
Here is the problematic part of the view.
#Html.PagedListPager((IPagedList)Model, page => Url.Action("SameNameAction", "SameNameController", new { page, pageSize= 5}))
Here is the routing definition in program.cs. As you can see, it's just basic stuff.
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
I expect that Url.Action would generate an url to the get action of the MVC controller. Instead, it generates an url to the post action of the Web API controller.
This is what I got:
2
This is what I expect:
2
I've never experienced Url.Action generating routing to an API controller. I'm not sure this is due to pagelist combined with url.action or url.action alone.
I can change the action name of the API controller, and the URL is generated as expected. However, this is not the issue. I would like to know why it map to the API controller and not the MVC controller to begin with.
I expect that Url.Action would generate an url to the get action of
the MVC controller. Instead, it generates an url to the post action of
the Web API controller.
Based on your scenario, I have checked your code between the line. As you know \[Route("")\] Attribute always has the higher precedence in routing therefore, this output/api/SameNameController?page=2&pageSize=5is obvious. However, using Url.RouteUrl HTML helper you can overcome your issue.
Solution:
#Html.PagedListPager((IPagedList)Model, page => Url.RouteUrl("default", new{httproute = "", controller="SameName",action="SameNameAction",page=1, pageSize= 5}))
Note: Please fit the code as per your environment.The exact code should be as folloing:
#Url.RouteUrl("default", new{httproute = "", controller="SameName",action="SameNameAction",page=1, pageSize= 5})
Output:
Hope it will guide you accordingly.

Attribute routing in different controllers results in "Multiple controller types were found that match the URL" [duplicate]

This question already has answers here:
Multiple Controller Types with same Route prefix ASP.NET Web Api
(3 answers)
Closed 5 years ago.
I am developing an application in .NET WebApi2 but I have a problem with the attribute routing when trying to split a controller in two. Both controllers have an action that is routed via /api/users/ but one is a GET and the other a POST.
But I am getting the exception Multiple controller types were found that match the URL. In a way it makes sense because it's true what the exception says, but as they have a different HttpMethod I'd expect this to work.
When putting both actions into the same controller, it works fine, which tells me that the framework does take the HttpMethod into account when matching the URI against an action.
So is there a way to make this work or am I forced to put both actions into the same controller?
[RoutePrefix("api/users")]
public class UserManagementController : ApiController
{
[HttpPost]
[Route]
public async Task<IHttpActionResult> CreateUser([FromBody] CreateUserInputModel input)
{
// ...
}
}
[RoutePrefix("api/users")]
public class UserController : ApiController
{
[HttpGet]
[Route]
public async Task<IHttpActionResult> GetAllUsers()
{
// ...
}
}
Routing is what determines what controller to use. But there is nothing built into routing (in Web API 2, anyway) that can tell the difference between a Get and a Post. By the time the request is handed off to the action invoker, it is already too late to go back and change the controller.
So, to fix this the best option is to use IHttpRouteConstraint to put further criteria on the route whether to match HttpGet or HttpPost and then configure it accordingly.
See Multiple Controller Types with same Route prefix ASP.NET Web Api for an example.

REST API not returning expected results

I'm trying to follow the article Build RESTful API's with ASP.NET Web API to learn how to create a RESTful API.
I created the first project and controller, Contact.
public class ContactController : Controller
{
// GET: Contact
public string[] Index()
{
return new string[]
{
"Hello",
"World"
};
}
}
But when I load the URL in a browser, instead of getting the response described in the article (["Hello","World"]). The response I get is System.String[].
I don't understand what I'm missing.
BTW, the article is from 2013. Does anyone know of a good article that is perhaps a little newer?
What you have now is simple ASP.NET MVC controller. For Web API controller you should inherit your controller from ApiController instead of Controller:
public class ContactController : ApiController
Also action names should start with HTTP verb. If you'll send GET request to /api/contact endpoint you'll get error
The requested resource does not support http method 'GET'.
By default action name is not used in route for Web API controllers. If you'll check default route configuration, it will be api/{controller}/id. Correct action is selected via HTTP method of request. In your case it should be GetXXX or simply Get
You cannot Return regular primitives from the Web Apis. At least if not if you are using a regular MVC Web API from .net. So, if this is the case you could do something like
public class ContactController : Controller
{
// GET: Contact
public JsonResult Index()
{
return Json(new { value1: "Hello", value2: "world" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps

Controller hangs when opened using url in mvc 5

I'm new on asp.net mvc. I created a basic controller and I tried to open it using url. But rendering is not finished and my controller didn't display in several minutes. I did not change anything from default asp.net 5 mvc project also my controller's index method return only hello world string. I don't is there any problem on iis or VS. Any idea about that problem?
Thanks for help.
In MVC only public methods that return an ActionResult are accessible as web pages.
So you MUST use something like this:
public class HelloWorldController : Controller
{
// GET: HelloWorld/Index
public ActionResult Index()
{
return Content("This is <b>Index</b> action...");
}
// etc
}
Content(...) is a special method the wraps text into an ActionResult.
Note: only use Content(...) if you specifically do NOT want to use a View such as Index.cshtml - which is what you normally WOULD do, of course.

Multiple controller types were found that match the URL. ASP.Net MVC

This is regarding defining routes using route attribute. I have two controllers
1st Controller
[AllowAnonymous]
[Route("Member/Login")]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
2nd Controller
[Route("{CategoryURL}/{Keywords}")]
public ActionResult BrowseProducts(string CategoryURL, string Keywords)
{
}
I am getting below error If try to access URL xyz.net/Member/Login
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
The request has found the following matching controller types:
XYZ.Controllers.AccountController
XYZ.Controllers.CoursesController
I am aware that I have Optional Parameters for second controller, hence when I try to access xyz.net/Member/Login, it finds two action methods to go for and getting the Multiple controller error.
My question is, how could I fix this issue without changing my current Routings. I tried Order, Precedence but nothing worked out.
As I commented above, based on your elected tags you are using MVC 4 yet attribute routing is supported in MVC 5. If you really are in MVC 5, then the following reference would be very helpful for you:
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
Most importantly, it's crucial that when you register your routes you active attribute routing -->
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}
And also ensure you don't have any other routes being defined that could confict with the attributes you've elected to use.
Otherwise your selected attribute should work fine. Pretty simple application.
The web api constraints may also aply for what you are trying to accomplish
http://www.asp.net/web-api/overview/web-api-routing-and-actions

Categories