asp.net - how to get value from post method - c#

In asp.net app i receive a form values from angular app.
[HttpPost]
public IActionResult addChange([FromBody] Change change)
{
return Json(change.Status);
}
How to get object or some value of object to use it in another class?

You should be able to access property like that: change.PropertyName.
But you might send data from angular as FormData, then you should change [FromBody] to [FromForm].
It's most likely that you are doing something wrong at angular site. You should check this endpoint via postman.
Edit:
To use this object in another method you should pass it through.
[HttpPost]
public IActionResult addChange([FromBody] Change change)
{
AnotherMethod(change);
return Json(change.Status);
}
public void AnotherMethod(Change change)
{
var foo = change.Status;
}

Related

Angular4 http.post .NET Core MVC bind failure

Tried a lot of solutions to pass an object from Angular4 service to c# controller. Although I do have the object received in service, does not bind to c# controller and so, I receive null.
Angular service:
getShedule(payload: any) {
this._http.post("Shedule/GetSchedule", payload)
.map(res => res.json()).subscribe((x) => {
console.log("callback succes");
});
}
C# controller:
[HttpPost]
public void GetSchedule(object priceScheduleObject)
{
//logic here
}
Any help is welcome.
Try to change your C# controller to
[HttpPost]
public void GetSchedule([FromBody] JObject priceScheduleObject)
{ /
The [FromBody] annotations let the ASP.NET Core Binding logic look into the body of the message (and not posted form fields).
If your do not want to interact with the JObject representing the JSON data you can bind the data to a model like
public class PriceSchedule {
public string Name {get; set;} // just an example, propert names depend on your json
...
}
[HttpPost]
public void GetSchedule([FromBody] PriceSchedule priceScheduleObject)
{ /

How to RedirectToAction with a model passed?

I have an model class that is used to validate some user input.
I have an controller with the following.
public IActionResult Checkout(GiftCard giftCard)
{
}
I was wondering how I could on an different action redirect it back to it such as
public IActionResult Preview(GiftCard giftCard)
{
return RedirectToAction("Checkout");
}
The above doesn't work because asp.net is trying to find an action without the model like the one below
public IActionResult Checkout()
{
}
if your url going to be really long make a shorturl so load that and redirect from there, if you use ajax it wont be visible
You could use action with another name and apply action selector to your renamed method. Like next:
[ActionName("Checkout")]
[HttpPost] //Recomend you send user input via post
[ValidateAntiForgeryToken] // and use validation token
public IActionResult CheckoutConfirmed(GiftCard giftCard)
{
//your code
}
public IActionResult Checkout()
{
//your code
}
Check out more about ASP.NET MVC - Selectors
If you need more information about ValidateAntiForgeryToken, you could find it there - Chapter 12: Security
And also, you could find great article about posting there - ASP.NET MVC Preview 5 and Form Posting Scenarios
RedirectToAction has a second parameter called routeValues with which you can pass the GiftCard like following.
public IActionResult Preview(GiftCard giftCard)
{
return RedirectToAction("Checkout", giftCard);
}

Getting angular ajax data in asp.net mvc6

I've been trying to figure this out for hours now but none of the solutions seem to help. I have an MVC6 project with AngularJs. I am able to connect, so my routes are working, and I am able to get data back if I hard code a string or something, but I can't seem to access the data sent to the server.
My angularjs http request code:
var app = angular.module('APIService', []);
app.factory('APIService', function ($http) {
var api = {};
api.getBuyer = function (data) {
return $http.post('/api/buyer', data);
}
return api;
});
The angularjs function call
APIService.getBuyer({ Url: 'samirbashir5739', FirstName: 'Samir' }).success(function (res) {
});
My C# Controller
namespace Reporting.api
{
[Route("api/buyer")]
public class BuyersController : Controller
{
// POST api/buyer
[HttpPost]
public string Post([FromBody] string Url)
{
return Url;
}
}
}
I've tried setting the data as "JsonResult data", or even "string Url." Most tutorials I found had an object for the data so it would fit into something like "[FromBody] Buyer buyer" but I don't have an object for it, I simply want the data. Is it possible?
WebApi does not support multiple parameter binding from a post request. You can check more details here.
So the proper way for the WebApi is to create a request model that will contain all the properties that will be bound. Perhaps you can try multiple [FromUri] parameters, but then you will have to add them to the url yourself in angualr, rather than just pass to .post.
Example model:
public class RequestModel
{
public string Url {get;set;}
public string Name {get;set;}
}
I also believe that adding the model improves the structure of your code as you always know what your server expects rather than working with some dynamic data.
P.S. Did not notice that you use ASP.Net Core, my data is from web api 2, but perhaps it's still valid, so you will need to create a model + FromBody should not be required on post requests since it's the default behavior.
I think your controller is wrong. You are trying to pass a Url and a name whereas your controller method is waiting for a single Url.
Try to pass only a Url and it should work.
If you want to pass the Url and the Firstname, you have to modify your controller method like this :
[HttpPost]
public string Post([FromBody] string Url, string FirstName)
{
// Do whatever you need to do here ...
}

ASP.NET Web API 2, how to distinguish methods with similar url

My team are using ASP.NET Web API framework.
In our application, we have 2 method which look like this:
[Route("users/events"]
[HttpGet]
public UserEvent GetEventsAssociatedWithUser(string Id) { ... }
and
[Route("users/{Id}"]
[HttpGet]
public User GetUserInformation(string Id) { ... }
but whenever I want to send request to "...users/events", it keeps send it to "...users/{Id}" and use "events" as an URI parameter.
I just want to know if there is any way to solve this problems without changing the URL of any of these method?
You need to set a route order like this
[Route("users/events", RouteOrder = 1)]
Read more here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#order
You need to use the RouteOrder parameter
See here:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#order
Example:
[Route("users/events" RouteOrder = 1]
[HttpGet]
public UserEvent GetEventsAssociatedWithUser(string Id) { ... }

Correct way to call WebApi RTM from an mvc4 application

So there is a heap of examples around but finding ones that are relevant to the rtm bits seems to be a little harder to find.
I have 2 projects one is an WebApi & the other is MVC4 .net 4.5 application.
I want to make a make an update to an item
I have a controller within my API that does something like
[HttpPut]
public MyModel Update(MyModel model)
{
//make update
return model;
}
Is this correct? should I be using a HttpResponseMessage instead of just using my MyModel class? I want to return the correct httpstatus details as much as possible as I am wanting to open up this api to 3rd parties not just my application
Calling this api from my mvc application from my controller how do I do this?
The beste way is to use HttpResponseMessage like this:
[HttpPut]
public HttpResponseMessage Update(MyModel model)
{
if(notfound)
{
return this.Request.CreateResponse(HttpStatusCode.NotFound);
}
//make update
return this.Request.CreateResponse<MyModel>(HttpStatusCode.OK, Model);;
}
I mostly use EasyHttp if I want want to call a WebApi method from my MVC app:
var model = new ExpandoObject(); // or use a stronly typed class.
model.Id = 1,
model.Name = "foo"
var http = new HttpClient();
http.Post("url", model, HttpContentTypes.ApplicationJson);
If you want to respond with httpstaus code you have to return HttpResponseMessage.
You may choose to have a common method returning your BOs and call it from the Action and from your other mvc application code. Then your rest calls would always be wrapped with a status code and other calls get an object.
[HttpPut]
public MyModel Update(MyModel model)
{
return base.Request.CreateResponse<MyModel>(HttpStatusCode.OK, UpdateModel(model));;
}
[NonAction]
internal MyModel UpdateModel(MyModel model)
{
//make update
return model;
}

Categories