I make a GET request, containing a passed in ID param, to my Controller, which in turn calls a backend script. I had no issues doing this in POST, but I'm confused as to how I should change my route in order to pass this ID param to the Controller.
Any help appreciated.
Code:
async getInfoAsync(id) {
const origin = new URL(window.location.href).origin;
const addr =
`${origin}/home/testApp/current_ticket_id` +
new URLSearchParams({ id: 1 }).toString();
try {
let response = await fetch(`${addr}`);
return await response.json();
} catch (err) {
console.error(err);
}
},
forwardTicketId() {
this.getUserAsync(this.ticketId).then((data) => console.log(data));
alert("Forward ticket ID hit");
},
async goNext() {
if (this.flagTriggered) {
this.loading = true;
await this.forwardTicketId(this.ticketId);
this.loading = false;
}
this.navGoNext();
},
Route:
def draw_id_route
scope 'zdeks', controller: 'lookup_id' do
get 'current_ticket_id/:id', action: 'tickets'
end
end
Controller Method:
def tickets
data = params[:id]
end
Error:
ActionController::RoutingError (No route matches [GET] "/home/testApp/current_ticket_idid=1"):
Related
Routes code below:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Controller code below :
// POST api/values
[HttpPost]
public void Post([FromBody]Employee employee)
{
employeeManager.CreateAsync(employee);
}
All other methods working except the post method.
call from angular component :
onSubmit(employeeItems: any) {
console.log(employeeItems);
this.getData();
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('api/Employee/Post', employeeItems, { headers: headers }).subscribe();
this.createEmployeeFlag = false;
}
I tried even from Postman, but no luck.
Your url and route templates do not match
[Route("api/[controller]")]
public class EmployeeController : Controller {
[HttpPost]
public async Task<IActionResult> Post([FromBody]Employee employee) {
await employeeManager.CreateAsync(employee);
return Ok();
}
}
and update your calling URL to call the default endpoint api/Employee
onSubmit(employeeItems: any) {
console.log(employeeItems);
this.getData();
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('api/Employee', employeeItems, { headers: headers }).subscribe();
this.createEmployeeFlag = false;
}
This is the code that you would need in your service, there are two issues here, first is the URL, it needs to be the complete URL path. The second is is that you are trying to subscribe to something before mapping it to a Observable
onSubmit(employeeItems: any) {
let url: string = 'http://localhost/api/employee'; //this will be the complete url that you would hit with say postman
this.getData(); //I'm not sure what this is so I'm leaving it here
this.http.post(url, employeeItems)
.map((response: Response) => response.json())
.Subscribe((response: any) => {
//do whatever with the response here.
});
this.createEmployeeFlag = false;
}
I would suggest breaking this up into a *.service.ts file.
*.service.ts
public postEmployee(employeeItems: any): Observable<any> {
let url: string = 'http://localhost/api/employee'; //this will be the complete url that you would hit with say postman
this.http.post(url, employeeItems)
.map((response: Response) => response.json());
}
inside your *.component.ts
constructor(private service: Service) {}
onSubmit(employeeItems: any) {
this.getData(); //I'm not sure what this is so I'm leaving it here
this.service.postEmployee(employeeItems)
.Subscribe((response: any) => {
//do whatever with the response here.
});
this.createEmployeeFlag = false;
}
I am initiating a post request from Angular2 to a ASP.NET 5 controller action. Angular is posting the data correctly and hitting the controller action but it is not being mapped to the parameters defined in controller action, the parameters are null. Meanwhile by inspecting through Request object Request.Form has the correct textual data but not binding to the model.
Angular
let body = JSON.stringify({ firstName: 'Ali' });
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
this.http.post(this.url, body, { headers: headers })
.subscribe(
(data) => {
console.log('Response received');
console.log(data);
},
(err) => { console.log('Error'); },
() => console.log('Authentication Complete')
);
ASP.NET
[HttpPost]
public IActionResult DemoAction(string firstName)
{
var req = Request;
return null;
}
Request.Form has data in the form like {\"firstName\":\"Ali\"} but the parameter firstName is null
You try to send a JSON content (created using the JSON.stringify method) with a content type url encoded form.
You should try to use the application/json one:
let body = JSON.stringify({ firstName: 'Ali' });
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(this.url, body, { headers: headers })
Edit
If you want to provide a form content, you could leverage the URLSearchParams class:
var params = new URLSearchParams();
params.set('firstName', 'Ali');
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
this.http.post(this.url, params.toString(), { headers: headers })
In this case you don't require to pass the header. look at here. you may try this.
this.http.post('/api/ControllerName/DemoAction?firstName=Ali')
.subscribe(
(data) => {
console.log('Response received');
console.log(data);
},
(err) => { console.log('Error'); },
() => console.log('Authentication Complete')
);
This will surely work.
Edited:
Figured out your problem.
First: When you are receiving paramter(s) at API end , you must use above portion.
second: When you are receiving object at API end, you must use below code.
I'm showing you with my setup as I don't know your object at server side.
let um=JSON.stringify({ Username: "Hello1",Password:"Hello2"});
let headers = new Headers({ 'Content-Type': 'application/json'});
this.http.post(this.url+'/Authentication',um,{ headers: headers })
.subscribe(...);
At server side I have following setup.
public class UserModel
{
public string Username { get; set; }
public string Password { get; set; }
}
[HttpPost]
public IHttpActionResult Authentication(UserModel um) // I m getting value here.
{
if (um.Username == "a" && um.Password == "a")
{
um.Username = um.Username;
um.Password = um.Password;
return Ok(um);
}
return NotFound();
}
Simple solution !! isn't it?
For me it works:
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(this.url, JSON.stringify({ firstName: 'Ali' }), { headers: headers })
I am using angularjs-rails-resource , in my Rails Angular App.
Account Resources
myApp.factory('Account', ['railsResourceFactory','railsSerializer', function
(railsResourceFactory,railsSerializer) {
return railsResourceFactory({
url: '/accounts',
name: 'account',
serializer: railsSerializer(function () {
this.nestedAttribute('address');
})
});
}]);
UserController.js
function userController($scope,$location,Auth,$rootScope,$http,Useraccount,Account) {
$scope.profileUpdate = function() {
//Useraccount.save(); // THIS WORKS
$scope.account = {}
$scope.account.save() // Throwing error : undefined function save
}
}
UserAccount Service
myApp.service('Useraccount',function(Auth,$location,$rootScope,Account){
var account;
var query = function(){
var promise = Account.query().then(function (results) {
account = results;
}, function (error) {
alert("Went Wrong while fetching User Account!!")
});
return promise;
}
var save = function() {
account.save().then(function (results) {
console.log(results);
}, function (error) {
alert("Went Wrong!!")
});
}
return {
query:query,
save:save
}
})
});
I am not sure why the save function from UserController is not working though I have imported Account resources as dependency. I did same in service , but it was working there. Any clue will be helpful.
You are actually calling the save() method for an empty javascript object. I don't see the point here.
Anyway you need an Angular object to do so. So either load account data from server.
$scope.accounts = Account.query(); // Will be an Array of accounts
Or create new instance of Account
$scope.account = new Account(); // An empty object
I am trying to change a value in a table from one view, and then redirect to another view using Flash FSCommand and Json, using the following code:
if (command == "nameClip") {
var url = '<%= Url.Action("Index", "Home") %>';
var clip = [args];
try {
$.post(url, {
MovieName: clip
}, function(data) {
;
}, 'json');
} finally {
// window.location.href = "/Demo/SWF";
}
}
In the controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SWF movietoplay) {
var oldmovie = (from c in db.SWFs where c.ID == "1" select c).FirstOrDefault();
var data = Request.Form["MovieName"].ToString();
oldmovie.SWFName = data;
db.SubmitChanges();
return RedirectToAction("Show");
}
All works well except Redirect!!
You need to perform the redirect inside the AJAX success callback:
$.post(url, { MovieName: clip }, function(data) {
window.location.href = '/home/show';
}, 'json');
The redirect cannot be performed server side as you are calling this action with AJAX.
Also you indicate in your AJAX call that you are expecting JSON from the server side but you are sending a redirect which is not consistent. You could modify the controller action to simply return the url that the client needs to redirect to using JSON:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SWF movietoplay)
{
...
return Json(new { redirectTo = Url.Action("show") });
}
and then:
$.post(url, { MovieName: clip }, function(data) {
window.location.href = data.redirectTo;
}, 'json');
I am fetching records for a user based on his UserId as a JsonResult...
public JsonResult GetClients(int currentPage, int pageSize)
{
if (Session["UserId"] != "")
{
var clients = clirep.FindAllClients().AsQueryable();
var count = clients.Count();
var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
var genericResult = new { Count = count, Results = results };
return Json(genericResult);
}
else
{
//return RedirectToAction("Index","Home");
}
}
How to redirect to a controller action from a JsonResult method in asp.net mvc?Any suggestion...
EDIT:
This doesn't seem to work...
if (Session["UserId"] != "")
{
var clients = clirep.FindAllClients().AsQueryable();
var count = clients.Count();
var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
var genericResult = new { Count = count, Results = results ,isRedirect=false};
return Json(genericResult);
}
else
{
return Json({redirectUrl = Url.Action("Index", "Home"), isRedirect = true });
}
This will depend on how you are invoking this controller action. As you are using JSON I suppose that you are calling it in AJAX. If this is the case you cannot redirect from the controller action. You will need to do this in the success callback of the AJAX script. One way to achieve it is the following:
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
And in the success callback:
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
Remark: Make sure to include isRedirect = false in the JSON in case you don't want to redirect which is the first case in your controller action.
Adding to Darin Dimitrov's answer. For C#.NET MVC - If you want to redirect to a different page/controller and want to send an Object/Model to the new controller, You can do something like this.
In the JsonResult Method (in the controller):
ErrorModel e = new ErrorModel();
e.ErrorTitle = "Error";
e.ErrorHeading = "Oops ! Something went wrong.";
e.ErrorMessage = "Unable to open Something";
return Json(new
{
redirectUrl = Url.Action("Index", "Home",e),
isRedirect = true
});
And in the success callback:
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
And if the new controller can accept the model/object like below.. you can pass the object to the new controller/page
public ActionResult Index(ErrorModel e)
{
return View(e);
}
Hope this helps.
What to do you think about trying to call:
return (new YourOtherController()).JSONResultAction();
instead of using redirects?
And if you work with areas ...
Controller:
return Json(new
{
redirectUrl = Url.Action("Index", "/DisparadorProgSaude/", new { area = "AreaComum" }),
isRedirect = true
});
View:
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
},
No way to do this, the client is executing an AJAX script so will not be able to handle anything else.
I suggest you redirect in the client script based on the returned data in the callback function.
Take a look at a similar question here: http://bytes.com/topic/javascript/answers/533023-ajax-redirect