i konw that you can have a period in a querystring parameter, but you cant specify a period in variable names in .net.
The following code obviously does not work, but my external system uses the period in the names. Is there a way to do this?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string hub.mode)
{
return View();
}
You could read the value directly from the Request hash:
[HttpPost]
public ActionResult Index()
{
string hubMode = Request["hub.mode"];
return View();
}
or using an intermediary class:
public class Hub
{
public string Mode { get; set; }
}
[HttpPost]
public ActionResult Index(Hub hub)
{
string hubMode = hub.Mode;
return View();
}
As you will notice . has special meaning for the ASP.NET MVC default model binder.
Related
I have the following code
public class BooksController : Controller
{
[Route("/Books/{id?}")]
public IActionResult Index(string id)
{
return View(id);
}
}
My problem is that when I try to enter the parameter it is (as it seems) considered as controller's action so I keep getting this exception.
I need somebody to explain what am I doing wrong.
If you want to pass some parameter to a view as a string you can make this like below:
public class BooksController : Controller
{
[Route("/Books/{id?}")]
public IActionResult Index(string id)
{
if (string.IsNullOrEmpty(id))
id = "default_value";
return View((object)id);
}
}
If the string type is passing to the View() call without casting to object it will be interpreted as a view name.
And the view model data should be declared as
#model string;
<h2>#Model</h2>
Try changing the route as given below -
[Route("Books", Name = "id")]
I'm working on implementing the Nexmo API into my code and have run into some issues with the controller. I'm getting the error
AmbiguousMatchException: The request matched multiple endpoints. Matches:
gardenplanning.Controllers.SMSController.Send (gardenplanning)
gardenplanning.Controllers.SMSController.Send (gardenplanning)
Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
I have a feeling that it has to do with the 2 "Send" methods however I'm out of ideas as to how to modify one of them to fix the routing. The code integrated into my project is below. I commented out the Index method because in my HomeController it already has method that maps to Index. Any help as to what's causing the issue would be appreciated, thanks.
enter code here
namespace gardenplanning.Controllers {
public class SMSController : Controller
{
/*
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
*/
//Send Action Method
[System.Web.Mvc.HttpGet]
public ActionResult Send()
{
return View();
}
//Action method containing "to" and "text" params
[System.Web.Mvc.HttpPost]
public ActionResult Send(string to, string text)
{
var results = SMS.Send(new SMS.SMSRequest
{
from = Configuration.Instance.Settings["appsettings:NEXMO_FROM_NUMBER"],
to = to,
text = text
});
return View();
}
}
}
The guide for Nexmo API is below
public ActionResult Index()
{
return View();
}
[System.Web.Mvc.HttpGet]
public ActionResult Send()
{
return View();
}
[System.Web.Mvc.HttpPost]
public ActionResult Send(string to, string text)
{
var results = SMS.Send(new SMS.SMSRequest
{
from = Configuration.Instance.Settings["appsettings:NEXMO_FROM_NUMBER"],
to = to,
text = text
});
return View("Index");
}
AmbiguousMatchException: The request matched multiple endpoints. Matches: gardenplanning.Controllers.SMSController.Send (gardenplanning) gardenplanning.Controllers.SMSController.Send (gardenplanning) Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
As exception message indicated, the request matched two or more endpoints, which cause the issue.
To resolve ambiguous actions you can try to apply different HTTP verb templates to these two "Send" action methods, which constrains matching to requests with specific HTTP method only. And in ASP.NET Core app, you can use [Microsoft.AspNetCore.Mvc.HttpGet] instead of [System.Web.Mvc.HttpGet].
[HttpGet]
public ActionResult Send()
{
return View();
}
//Action method containing "to" and "text" params
[HttpPost]
public ActionResult Send(string to, string text)
{
var results = SMS.Send(new SMS.SMSRequest
{
from = Configuration.Instance.Settings["appsettings:NEXMO_FROM_NUMBER"],
to = to,
text = text
});
return View();
}
Besides, if you'd like to conditionally enable or disable an action for a given request based on query string, you can try to implement a custom ActionMethodSelectorAttribute. For more information, please check this blog:
https://devblogs.microsoft.com/premier-developer/defining-asp-net-core-controller-action-constraint-to-match-the-correct-action/
How to generate some URL like http://mysite/some-id using below method?
Note: I do not want to use controller name and action name in url. because the main site used this structure and my boss does not want to change it.
public class StoryController : Controller
{
public ActionResult Index(string id)
{
if(id =="some-id"){
}
return View();
}
}
I don't know what version of MVC you are using, but if you are on the newest version or .NET Core, if you used routing attributes, you'd achieve this by:
[Route("")]
public class StoryController : Controller
{
[Route("{id}")]
public ActionResult Index(string id)
{
if(id =="some-id"){
}
return View();
}
}
Having a single parameter that is a string on your index-like route will definitely pose problems later with the routing engine though, when you try to add more controllers and views
I am trying to receive a HTTP POST from Mirth Connect in my ASP.NET MVC solution but I donĀ“t know how this data comes to my web application. I create a controller to receive it:
public class IntegrationController : Controller
{
public ActionResult Index()
{
var c = HttpContext.CurrentHandler;
var v = c.ToString();
Console.Write("The value is" + v);
return View();
}
}
What should I receive in Index()? A dictionary? And once I receive it, how to how it in the viewer?
Thank you.
I use the [FromBody] Annotation, then I can treat the incoming like any other parameter.
[Route("api/gateways")]
[Route("api/connectedDevices")]
[Route("api/v0/gateways")]
[Route("api/v0/connectedDevices")]
[HttpPost]
public HttpResponseMessage Create([FromBody] IGatewayNewOrUpdate device,
I do have a case when I read the content directly from the Request;
[HttpPost]
public HttpResponseMessage AddImageToScene(long id, string type)
{
SceneHandler handler = null;
try
{
var content = Request.Content;
I think it may be a little different for different versions, but I hope that will give you a starting point.
Try something like this. This will work, if v is the name of a field that will be posted from a form.
public class DataModel
{
public string v {get; set;}
}
public class IntegrationController : Controller
{
[HttpPost]
public ActionResult Index(DataModel model)
{
Console.Write("The value is" + model.v);
return View();
}
}
If you receive Json then a can add [FromBody]
public class IntegrationController : Controller
{
[HttpPost]
public ActionResult Index([FromBody] DataModel model)
{
Console.Write("The value is" + model.v);
return View();
}
}
This question already has answers here:
MVC [HttpPost/HttpGet] for Action
(4 answers)
Closed 2 years ago.
Why is this incorrect?
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
public ActionResult Index()
{
Some Code--Some Code---Some Code
return View();
}
}
How can I have a controlller thas answer one thing when is "getted" and one when is "posted"?
Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:
[HttpGet]
public ActionResult Index()
{
// your code
return View();
}
[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
// your code
return View();
}
Also see "How a Method Becomes An Action"
While ASP.NET MVC will allow you to have two actions with the same name, .NET won't allow you to have two methods with the same signature - i.e. the same name and parameters.
You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.
That said, if you're talking about a GET and a POST, this problem will likely go away, as the POST action will take more parameters than the GET and therefore be distinguishable.
So, you need either:
[HttpGet]
public ActionResult ActionName() {...}
[HttpPost, ActionName("ActionName")]
public ActionResult ActionNamePost() {...}
Or,
[HttpGet]
public ActionResult ActionName() {...}
[HttpPost]
public ActionResult ActionName(string aParameter) {...}
I like to accept a form post for my POST actions, even if I don't need it. For me it just feels like the right thing to do as you're supposedly posting something.
public class HomeController : Controller
{
public ActionResult Index()
{
//Code...
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
//Code...
return View();
}
}
To answer your specific question, you cannot have two methods with the same name and the same arguments in a single class; using the HttpGet and HttpPost attributes doesn't distinguish the methods.
To address this, I'd typically include the view model for the form you're posting:
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
public ActionResult Index(formViewModel model)
{
do work on model --
return View();
}
}
You received the good answer to this question, but I want to add my two cents. You could use one method and process requests according to request type:
public ActionResult Index()
{
if("GET"==this.HttpContext.Request.RequestType)
{
Some Code--Some Code---Some Code for GET
}
else if("POST"==this.HttpContext.Request.RequestType)
{
Some Code--Some Code---Some Code for POST
}
else
{
//exception
}
return View();
}
Can not multi action same name and same parameter
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(int id)
{
return View();
}
althought int id is not used
You can't have multiple actions with the same name. You could add a parameter to one method and that would be valid. For example:
public ActionResult Index(int i)
{
Some Code--Some Code---Some Code
return View();
}
There are a few ways to do to have actions that differ only by request verb. My favorite and, I think, the easiest to implement is to use the AttributeRouting package. Once installed simply add an attribute to your method as follows:
[GET("Resources")]
public ActionResult Index()
{
return View();
}
[POST("Resources")]
public ActionResult Create()
{
return RedirectToAction("Index");
}
In the above example the methods have different names but the action name in both cases is "Resources". The only difference is the request verb.
The package can be installed using NuGet like this:
PM> Install-Package AttributeRouting
If you don't want the dependency on the AttributeRouting packages you could do this by writing a custom action selector attribute.
Today I was checking some resources about the same question and I got an example very interesting.
It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:
#using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { #id = "form-consulta" }))
{
//code
}
The action:
[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}
By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.
When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.