Getting a POST variable - c#

I am using C# with ASP.NET.
How do I check if a parameter has been received as a POST variable?
I need to do different actions if the parameter has been sent via POST or via GET.

Use this for GET values:
Request.QueryString["key"]
And this for POST values
Request.Form["key"]
Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:
Request["key"]
Another thing to note (if you need it) is you can check the type of request by using:
Request.RequestType
Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

Use the
Request.Form[]
for POST variables,
Request.QueryString[]
for GET.

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.
if (Page.IsPostBack)
{
// HTTP Post
}
else
{
// HTTP Get
}

Related

asp.net cleanest way to pass object to ActionResult

Currently, our application has a lot of ActionLinks that only pass an id to the controller, where the object is retrieved again (that was already present/known on the previous page). Is there any cleaner way to do this, like pass the object instead? As our backend isn't too quick it takes a few seconds to load in the popup which you get after you click on the ActionLink.
I've seen some solutions using ajax to post the object but that doesn't seem like the neatest solution to paste those js lines under/at every ActionLink that is used in combination with a popup.
The #Html.ActionLink() method will generate a url link to the given Controller/Action. Thus, it can only contain parameters that can be contained in the url of the link. So you cannot pass an object through on the url.
If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).
Parameters in the ActionLink are set through the collection that you passed in as the third item in your function call above. Assuming default routing, this would give an address that looks like /Admin/EditPage/?name=XXX where XXX is the value of menuitem.Title. If you included something else here like itemId = menuitem.Id then it would add this as a query string parameter to the url generated, which would then be accessible to the action that is the target of this link.

Umbraco 7 UmbracoAuthorizedApiController returns 405 (Method Not Allowed)

I'm creating a custom tree inside umbraco7 and and have a button which will call an UmbracoAuthorizedApiController called ExportApiController i added a constructor and set a breakpoint on it to see if this controller is indeed instanced and it is. But when i try to call the call my action it is returning an 405 (Method Not Allowed)
And in the response i see the following text
{"Message":"The requested resource does not support http method 'GET'."}
above my controller action i have the HttpGet attribute and i also tried the put or post but nothing helps. But i think that when i use post i need to do something else inside Angular to call it using a submit on a form? But i'm not sure how or why.
If you need more information please tell me and i will post it.
Thanks.
I had the same problem and for me the problem was that I accidently had HttpGetAttribute.HttpGet instead of System.Web.Http.HttpGet.
What is the name of your method ? I find that if you don't actually have "get" in the front of the name it would throw out this error so
public string CorrectTime(string time) < -- would fail but
public string GetCorrectTime(string time) <-- would pass
Because you want to export data, I guess you are trying to use this controller for the big public. However, UmbracoAuthorizedApiController are only for back-end users as mentioned in the documentation. You should not use these to expose data outside the Umbraco back-end.
If you want to expose data, and you want to validate against the members (not users) you should prefix your UmbracoApiController with the MemberAuthorize attribute

get current page in C#

For instance if I have http://www.mywebsite.com/about.aspx. Store about.aspx (or whatever page we're on) in a variable. Also need this to work even if there is information after the page in the url such as a query string.
Ah - I suggest you read the ASP.NET documentation VERY carefully. The HttpRequest object, available as Request property contains all information that you can have about the request. This includes the path called, all parameters etc.
Weighing in a little late, but others may get here as I did.
You could try to use a combination of the Uri and Path objects. For example:
Uri test = new Uri("http://www.microsoft.com/default.aspx?id=7&em=958");
Console.WriteLine(Path.GetFileName(test.AbsolutePath));
Not sure if this is the "proper" way but it works for me.

Handling post requests in ASP.NET MVC

Recently I started working with MVC, before that I used "classic" ASP.NET.
After using Ruby on Rails (RoR), I wonder how to implement POST request handling in MVC similar to how RoR operates. In RoR you use the Post method, so you need only one function for a view.
In ASP.NET MVC I need to use 2 separate functions for GET and for POST, so I need to initialize the same data twice, and I don't like to repeat something in my code.
How can I check if the request is POST in one method?
Update:
Solution is found: I have to use Request.HttpMethod.
Thank you!
I came across this question wanting to know the same thing. Below is a detailed description of my situation and the solution that I used (which utilizes the other answers provided here). I originally tried to use the two separate method approach, but I ran into a problem when the method signatures of these methods became identical.
I have a page that displays report data. At the top of the page there is a form with some fields, which allow the user to specify report parameters such as start date, end date, etc.
I originally approached this by creating two separate methods to handle the Get and the Post methods. The post method would redirect the browser to the get method so that any parameters that were specified would be added to the query string and so that the browser would not prompt the user with a dialog saying that it is going to resend the data that they entered if they refresh. Note: I realized later that I could accomplish this by setting the method attribute of my form element to "Get", but I think ideally a controller shouldn't have knowledge of how a view is implemented, so in my opinion that is irrelevant.
As I developed these two methods I eventually found myself in a situation where the method signatures became identical. Furthermore, my code for these two methods became nearly identical, so I decided to merge them into a single method and to just check the request verb so that I could do something slightly different when the request is not a "Get". A distilled example of my two methods is shown below:
// this will not compile because the method signatures are the same
public ActionResult MyReport(DateRangeReportItem report)
{
// if there are no validation errors and the required report parameters are completed
if (ModelState.IsValid && report.ParametersAreComplete)
{
// retrieve report data and populate it on the report model
report.Result = GetReportData(report.CreateReportParameters());
}
return View(report);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyReport(DateRangeReportItem report)
{
if (ModelState.IsValid && report.ParametersAreComplete)
{
// redirect to the same action so that if the user refreshes the browser it will submit a get request instead of a post request
// this avoids the browser prompting the user with a dialog saying that their data will be resubmitted
return RedirectToAction("MyReport", new { StartDate = report.StartDate, EndDate = report.EndDate });
}
else
{
// there were validation errors, or the report parameters are not yet complete
return View(report);
}
}
Why am I accepting a model object as the parameter to my get method? The reason is that I wanted to take advantage of the validation logic already built into the model object. If someone navigates to my page directly with all parameters already specified in the query string, then I want to go ahead and retrieve the report data and display it on the page. However, if the parameters specified in the query string are invalid then I also want validation errors to appear on the page. By putting my model object as the parameter, the MVC framework will automatically attempt to populate it and will capture any validation errors without any additional work on my part.
I used the other answers posted for this question to create a RequestHttpVerb property on a base controller class in my project:
public HttpVerbs RequestHttpVerb
{
get { return (HttpVerbs)Enum.Parse(typeof(HttpVerbs), this.Request.HttpMethod, true); }
}
So finally my consolidated method looks like the following:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult MyReport(DateRangeReportItem report)
{
// check if there are any validation errors in the model
// and whether all required report parameters have been completed
if (ModelState.IsValid && report.ParametersAreComplete)
{
// this is unnecessary if the form method is set to "Get"
// but within the controller I do not know for sure if that will be the case in the view
if (HttpVerbs.Get != this.RequestHttpVerb)
{
// redirect to the same action so that if the user refreshes the browser it will submit a get request instead of a post request
// this avoids the browser prompting the user with a dialog saying that their data will be resubmitted
return RedirectToAction("MyReport", new { StartDate = report.StartDate, EndDate = report.EndDate });
}
// there were no validation errors and all required report parameters are complete
// retrieve report data and populate that data on the model
report.Result = GetReportData(report.CreateReportParameters());
}
// display the view with the report object
// Any model state errors that occurred while populating the model will result in validation errors being displayed
return View(report);
}
That's my current solution to the problem. I would prefer not to have to check the Request.HttpMethod property in order to determine whether I needed to perform the redirect, but I didn't see another solution to my problem. I would have been fine with keeping two separate methods to handle Get and Post requests, but the identical method signature prevented this. I would have preferred to rename my Post action handler method to avoid the method signature conflict and to use some mechanism to indicate to the MVC framework that my renamed method should still handle the "MyReport" action, but I am not aware of any such mechanism in the MVC framework.
You only need separate methods for GET and POST if their method signatures differ, there's no reason why one action method can't handle GET and POST methods.
If you need to know whether it was a GET or POST, you could check using Request.HttpMethod in your action, but I would advise using a separate method decorated with the [AcceptVerbs(HttpVerbs.Post)] attribute as suggested by the other posters.
You don't check in ASP.NET MVC. You decorate your method with the [AcceptVerbs(HttpVerbs.Post)] attribute to indicate that the method applies to post only, and accept the model in the method used to handle the post.
I'd strongly suggest doing the walkthrough for NerdDinner to understand more about the ASP.NET MVC framework.
You may take a look at the Request.HttpMethod property.
Correct way to do is using ModelBinding during Post request.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(EmployeeViewModel model)
{
//validate data, save employee, handle validation errors...
}
This way you will not have to init your data again.

Alternative to Query Strings to Pass Data Between ASP.Net Pages?

I am currently using a number of query string parameters to pass some data from one page to a second page (the parameters hold confirmation/error messages to display in the second page), that due to a third party product can no longer work correctly in the production environment. The user completes an action on the first page, and is then transferred to the second page. What are the possible alternatives to use instead of a query string and GET - session variables, POST data, or something completely different?
Thanks, MagicAndi.
You could create public properties in a source page and access the property values in the target page when using a server transfer. You could also get control information in the target page from controls in the source page by referencing the Page.PreviousPage property.
Both of these methods are oulined here: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
Both POST data and session variables would work just fine. POST data has the drawback that it can be changed by the client and session variables take up memory, so you can choose based on that. I personally don't think that you should pass such messages to the client for the reason stated above but I guess you are already doing that, so...
you can use this if you use window.open("openTheotherPage",...etc)
so form the opened page you can do something like this
var valuefromCallerPage = window.opener.document.FormNmae.textbox.value
or button or anything on the caller page

Categories