how to route form search words in asp.net? - c#

I am trying to understand asp.net server implementation and routing in particular. I have tried to search this forum for answers(for instance this link; WebApi 2.0 Routes not matching with query parameters?, but I havent gotten anything to work. I would like to have a form on the client side:
<"form id="search-form" name="search-form" method="get" action="page.html"
onsubmit="return validate();">
<"input id="inputText" name="question" type="text"
placeholder="Search..." class="inputsearch">
<"/form>
This will allow me to send a query (for instance "test") to the server, which would look like "page.html?question=test". My controller is called products (but it seems to me that I do not need to specify it in an action tag on the form, so I was thinking that I need some routing like:
[HttpGet]
[Route("~/api/products?{queryWord}")]
public IHttpActionResult test(string queryWord)
{
Debug.Write(queryWord);
return Ok("<html>hey</html>");
}
That seemed to be valid from the answers in that link, but I get an error message:
The route template cannot start with a '/' or '~' character and it
cannot contain a '?' character. Parameter name: routeTemplate

Related

#Url.Action("Action","Controller") calls both post and get method with same name

I have a controller where there are two action methods with same name with HttpPost and HttpGet as shown below , when link with #Url.Action("DoSomething","Controller") is called then both the method are invoked , how do I call only GET method?
Is there anyway to pass type GET or POST in #URL.Action or any other way?
[HttpGet]
public ActionResult DoSomething(int ? MyParam)
{
}
[HttpPost]
public ActionResult DoSomething(MyModel Model)
{
}
In Razor View When I build a link like
JustDoIt
Then it calls both POST and GET methods, even after specifiying parameter as int and not the model
Try adding post in the form declaration:
#using (Html.BeginForm("DoSomething","Controller", FormMethod.Post))
{
}
or using HTML:
<form action="#Url.Action("DoSomething","Controller")" method="POST">
...
</form>
The HTTP verb POST/GET will route your request to the appropriate action. The default is GET.
I think that you maybe getting Url.Action() confused with Html.Action() (apologies if I'm wrong). As someone mentioned in the comments, Url.Action() will just render a URL based on the parameters which is intended for say building anchor tags. Html.Action() on the other hand will invoke an action when building the page for the response at server side which I'm guessing is what your referring too.
If that's the case, then you will need to specify the Action's parameters for DoSomething() by specifying the route values like so:
#Html.Action("DoSomething", "Home", new {MyParam = 2} )
The result of DoSomething(int MyParam) would be injected into the page. Html.Action is not intended to call a POST so it's not possible to use this on an Action which has been decorated with the POST verb.
Issue was I was having one more ajax request to check if the page has been loaded completely to show progress bar, when removed that portion of the code from layout, It has been working fine without calling any action method twice.

Argument passed to controller is always null

I've been working on a relatively simple application in ASP.NET Core that displays the status of various nodes in a network. It displays their latest status, and some other information.
For this, I've made a controller which has an action that takes a node's name, performs a lookup in the node manager, and returns the detail view for that specific node. This controller action is implemented like so:
public IActionResult Detail(string name)
{
// Maybe redirect this to the node detail overview once it's done?
if (string.IsNullOrEmpty(name))
return View("PageNotFound");
var viewModel =
Current.NodeManager.Statuses.FirstOrDefault(s => s.Node.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (viewModel == null)
return View("PageNotFound");
return View(viewModel);
}
I'm linking to this action from my overview page. The HTML I'm using to do this is:
<a asp-area="" asp-controller="Node" asp-action="Detail" asp-route-id="#status.Node.Name">#status.Node.DisplayName</a>
For one of my nodes, this produces the following link:
http://example.com/Node/Detail/Temeria
And from what I understand from the ASP.NET Core documentation, the controller should capture "Temeria" here as the argument for the Detail action of NodeController, but it reliably refuses to do so. name here is always null.
I've also messed around with the routing in Startup.Configure, by adding the following route to the controller:
routes.MapRoute(
name: "Node Detail",
template: "{controller=Node}/{action=Detail}/{name}");
But unfortunately, to no avail. Every time I invoke the action, be it via clicking the link I've outlined above, or visiting the detail action manually by typing in the URL in my browser, ASP.NET Core spits out the following log line:
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method Aegis.Controllers.NodeController.Detail (Aegis) with arguments () - ModelState is Valid
I'm at a loss here - am I missing something really obvious here, or does ASP.NET Core not work with primitive types and should I resort to the "model binding" I've been seeing in the guides (which seems to be a bit overkill for an action as simple as this one)?
I've seen various other questions similar to this one, but none of them were for ASP.NET Core. I've done similar projects in classic ASP.NET, and never had this issue with that framework.
Any help would be greatly appreciated. Thanks for your time!
The key is in this line:
<a asp-area="" asp-controller="Node" asp-action="Detail" asp-route-id="#status.Node.Name">#status.Node.DisplayName</a>
I've changed asp-route-id to asp-route-name and everything works fine. So the answer is:
<a asp-area="" asp-controller="Node" asp-action="Detail" asp-route-name="#status.Node.Name">#status.Node.DisplayName</a>

Change url (redirection) in asp .NET

I am working on a C# mvc application. In my site I have this url abc.com/About/WhoWeAre, where 'About' is the Controller and 'WhoWeAre' is the action name. But i want this url to be returned as abc.com/About/who-we-are. The problem is I can't name the action containing '-' in it. I tried Url Redirection using HttpContext Response but couldn't find a solution.
If I handle the request in Route Config for 'About/who-we-are' and route it to 'About/WhoWeAre' it is working with the required url in the address bar. But when I make request for 'About/WhoWeAre' it returns the page with the same('About/WhoWeAre') url in the address bar, which duplicates the url. How can I redirect?
Feel free to ask any questions.
Use ActionName Attribute to map the Url. Below is the example
public class AboutController : Controller
{
[ActionName("Who-we-are")]
public ActionResult WhoWeAre()
{
return View();
}
}
You can use the ActionName attribute to rename your actions with characters that are disallowed in C# method names.

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

Adding HttpPost getting error 'The Resource Cannot Be Found' in MVC

I'm getting the 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: /ClientEdit/ClientEdit/1104
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
when I add HttpPost attribute to a controller. I've looked into this and corrected my code with posted(no pun intended) answers but nothing I've tried works. Here's my controller header:
[HttpPost]
public ActionResult ClientEdit(int id,FormCollection formCollection)
I added HttpPost so I can populate my FormCollection object. As with other SO posts, this causes the error. Removing it solves the issue but my FormCollection doesn't populate any key/value pairs.
My view has its form tag's method set to POST which solved other dev's issues but it doesn't solve mine. I tried adding 'name=' properties to my textbox controls as well as 'id=' but that doesn't work either.
<body>
<form method="post" action="1104" id="form1">
I don't know what else to try.
You need to provide you view that renders the <form> as well. The action on what you show as your HTML looks wrong to me. I would think it would be something like action="/Controller/ClientEdit".
you have given wrong value in the attribute action="1104".
Either you can specify proper route in action attribute or leave it if the route is same as of get.
This should work if GET and POST route are same
<form method="post" id="form1">
.....
</form>
use this:
#using(Html.BeginForm()){
<!--Your form field-->
}
Basically what is happening is that your action attribute is just pointing to the Id you have and not the url to post to.
You can do it manually like this:
<form action="ClientEdit/ClientEdit/1104>
<!--form fields-->
</form>
Yes, you are all correct. I was passing a userid as the action. This was legacy code that 'worked' for another feature but doesn't conform to the MVC pattern. I did some other research (as I'm not too familiar with MVC either) and started again from scratch using MVC as it should be. Thanks everyone.

Categories