Cant pass data from angular to Mvc controller - c#

Its is my Angular controller
var app=angular.module('app',[]);
app.controller('myCtrl', function ($scope,$http) {
console.log($scope.add)
$scope.asd = function (data)
{
$http({
url: '/Home/My',
method: "GET",
data: data
});
}
//console.log($scope.asd);
});
When im passing data like this it is working well
{
$http({
url: '/Home/My',
method: "GET",
params: { data: data}
});
}
Mvc controller
public ActionResult My(List<string> data)
{
return View();
}
But why couldnt i pass it with "data"?

Looking at the Angular documentation at https://docs.angularjs.org/api/ng/service/$http , it seems that the "params" parameter refers to data that you want to pass as HTTP GET parameters, while the "data" parameter simply dumps the content into the HTTP request.
Is there a specific reason why you want it to work the first way? If there is not, then the second way appears to be the more elegant choice as it strengthens the interface contract between your Angular and MVC components.

Related

ASP.NET Core MVC RedirectToAction isn't working

I have seen lots of questions regarding this issue but none of those resolved my problem.
My problem: my redirect action method hits the method I am redirected to, but the view stays on the same page it never changes to the redirected one.
From my Index.chstml I am creating a partial view.
From that partial view using AJAX I am submitting a request to my controller. AJAX code is below
$.ajax({
method: 'POST',
url: "/Home/SubmitTest",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
success: function (response) {
}
});
My controller code is here. I am receiving data from AJAX method and performing some jobs. In the end, I am trying to redirect the user to another method.
[HttpPost]
public IActionResult SubmitTest([FromBody] List<TestSubmitViewModel> data)
{
// Rest of the code goes here
return RedirectToAction(nameof(PipelineList));
}
The method I am redirecting to is below. Both methods are in the same controller. After redirection, I am getting hit to this method. But my view still stays in the previous URL which is
https://localhost:44339/Home/Index
but it supposed to redirected to
https://localhost:44339/Home/PipelineList
Code:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> PipelineList()
{
List<PipelineViewModel> itemList = new List<PipelineViewModel>();
/// my other code goes here
return View(itemList);
}
Note: my PipelineList() works fine when I am coming to this action method directly from UI. What am I doing wrong here and what can I do to redirect to the URL?
I am using .NET Core 5.
Here is my routing information from StartUp.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action="SignIn"});
});
UPDATE
Thank you guys for pointing out the problem I was having.
Using AJAX was necessary for me to pass the selected values (which were from a table created by JS) from UI.
Finally, I made it work by changing my Controller and AJAX code.
Updated Controller:
[HttpPost]
public async Task<JsonResult> SubmitTest([FromBody]
List<TestSubmitViewModel> data)
{
try
{
// my codes goes here
return Json(new {StatusCode = statusCode });
}
catch (Exception)
{
return Json(new {StatusCode = 500 });
}
}
Updated AJAX:
$.ajax({
method: 'POST',
url: "/Home/SubmitTest",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
success: function (response) {
if (response.statusCode == 200) {
var url = "/GitLab/PipelineList";
window.location.href = url;
} else {
alert("error");
}
}
});
I know this might not be the best solution but for now, it did work. Thanks a lot to #Sergey and #Filipe
As #Sergey says, you used the wrong senior for ajax. Ajax is normally used when you want to update part of the page instead of refreshing the whole page to increase the customer experience and page load speed. If you want to redirect to another page and there is no other specific reason, there is no need to use ajax.
You could find the ajax server has returned the right 302 redirect to the client side and it redirect to the new page:
The right way is directly redirect to the new page like this:
<form asp-action="SubmitTest" asp-controller="Home" method="post">
#*Other input value you want to submit*#
<input type="submit" value="Click"/>
</form>
Result:

C# MVC Calling a method in different path using AJAX

I have a HomeController in my ASP.NET MVC application in folder "Controllers". My View is in: "View/Home/Index.cshtml" (look at my figure below).
I am using Ajax to get some json file every a few second. Problem is in Ajax URL, because I really don't know and didn't find, how to tell that property, that it has to go back a few folders and then find the HomeController.
My Solution looks like this:
Here is a method in my HomeController:
[HttpGet]
public ActionResult GetRandomFeed()
{
Item i = ss.getRandomFeed();
return Json(new { Source = i.Media.Source, Avatar = i.User.Avatar, Text = i.Text, Name = i.User.Name }, JsonRequestBehavior.AllowGet);
}
My AJAX in the View:
setInterval(function () {
$.ajax({
type: "GET",
url: '/HomeController.cs/GetRandomFeed', // Of course I have tried a lots of attempts in here
contentType: "application/json;", // Not sure about this
dataType: "json",
success: function (response) {
console.log("Success :)");
},
error: function() {
console.log("Error!");
}
});
}, 2000);
All I want to get that JSON file (or can be even an array of strings) and use it in my Success function. It is a simple Slide Show and JSON contains the URLs that I want to show in the page every X seconds (just changing source of an image that is in that JSON file).
I couldn't find anything like this. How to use that URL correctly OR found something similiar for WebForms but cannot use it in MVC.
Change your AJAX URL declaration to:
url: '/Home/GetRandomFeed'
Remove the .cs
Or you can also do, assuming this view is under your controller:
url: '#Url.Action("GetRandomFeed")'
In my experience, it doesn't seem enter the function is just because the JSON return from the controller doesn't include Status = "OK"
[HttpGet]
public ActionResult GetRandomFeed()
{
...
...
return Json(new
{
Status = "Ok", ...
}

Ajax post not working MVC 5

I'm trying to post data into a controller but it doesn't seems to work, I need the post to include the content of the view into a div when done but I cant quite achieve it
Here's my js function:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: "Student/Schedule",
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').load(a);
}
});
}
And, here's my controller:
public ActionResult Schedule(String number)
{
return View(number);
}
I am a noob in MVC and C#, so any help is welcome.
There are somethings that you should fix to solve the problem.
Change Url to "/Student/Schedule"
You are using "Student/Schedule" as url, so you are trying to call an action named "Student".
Add [HttpPost] to your action.
You should return PartialView("Schedule", number);.
When you use return View(number) it uses the string value of number as your view name. You should explicitly pass view name and model.
Use $('#schedule').html(a);
It's better to add an error function to your ajax call to be able to find errors:
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
//or you can put jqXHR.responseText somewhere as complete response. Its html.
}
Your action should return a Partial View, not a View.
Change your action to:
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number)
{
return PartialView("_Schedule", number);
}
Then, you'll need to create a partial view named _Schedule.cshtml.
Also, you need to change $('#schedule').load(a); to $('#schedule').html(a); And, I'd suggest that you use a Url.Action to set your url in your ajax call, like this:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: '#Url.Action("Schedule", "Student")',
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').html(a);
}
});
}
I had the same issue what i did was adding jquery.unobtrusive-ajax.js to my scripts

Passing form data to a controller method using Ajax

Experts,
I have form data -
var formdata = JSON.stringify($('#emailrequest').serializeArray());
and a url -
var urlofRequest = window.location.href; //This url is of above Emailrequest form .
My question is -
How do we send these two - formdata and urlofRequest to a .cs(controller) method -
public JsonResult ProcessEmailrequest()
{
// What code and parameters?
}
The controller method which opens up the form is -
public ActionResult EmailRequest()
{
return View();
}
I have the below code but it does not seems to work -
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'GET',
data: formdata,
sucess: function (data) {
alert('DataPosted');
}
})
The type in the ajax call is GET; no data is being posted to the form. Try making it a post or put. example jquery ajax post Also keep in mind that you are posting form data, so you will need to have parameters on the post method ProcessEmailrequest on the supply-chain-pressure controller to catch the data. example of mvc post method This is a jquery/ajax example that does basically the same thing jquery/ajax example

ASP.NET MVC submit empty string to WebApi Controller on jquery serialize()

I'm trying to POST data from ASP.NET MVC View to WebApi Controller via j Query $.post(), but I'm always receiving just empty string (what's interesting - this work fine with Web Forms).
Here is JS.
$("#searchbtn").click(function () {
var ser = $("div#hotels").serialize();
$.post('/api/hotelsavailablerq', { '': ser });
});
Here is how ApiController signature look like:
[HttpPost]
public void PostHotelsAvailableRq([FromBody] string q)
View using just pure HTML forms - div, select, input type=text. Nothing Binded from model.
try another:
$.ajax({
url: '/api/hotelsavailablerq',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
data: JSON.stringify(ser)
});
Please try the below code to hit the controller. Make sure there is hotelsavailablerq action method in api controller.
$("#searchbtn").click(function () {
$.ajax({
url: '/api/hotelsavailablerq',
type: 'POST',
data: $('div#hotels').serialize(),
success: function (result) {
});});
Well, I found answer - RTFM.
When I read carefully jQuery documentation about serizlization, I found that:
1. <form> tag should exist.
2. Each control should have name attribute.
All these things has by default in web form, but in MVC I should add its manually.
Try
$.post('/api/hotelsavailablerq', { 'q': ser });
string q should be of the same type which you are sending from the jQuery.

Categories

Resources