call controller action from .cshtml page with jquery - javascript

I am trying to call a controller action from a jquery UI dialog.
What I have currently is this:
.html("<p><textarea name=\"TextMessage\" id=\"textItems\" rows=\"10\" cols=\"72\" /><br /><br /><input type=\"button\" style=\"float:right;\" id=\"submitData\" onclick=\"Test()\" value=\"Submit\" /></p>");
The script I am using to call the controller action is this one:
<script type="text/javascript">
function Test() {
$ajax({
url: '<%= Url.Action("GetData", "Report") %>',
success: function (data) {
alert(data);
}
});
};
</script>
And the controller action is this:
[HttpGet]
public JsonResult GetData()
{
return Json("success", JsonRequestBehavior.AllowGet);
}
I would like to know if I am doing something wrong, I am trying to get this to work but without any success. When I am trying directly to start the controller via http://localhost:1322/Report/GetData it works fine, so that means that the script is not setup properly.

You should try:
url:'#Url.Action("GetData", "Report")'
MVC will automatically add "Controller" to the end of the second parameter when it is looking for the controller.
Edit:
This code may work:
function Test() {
$.ajax({
type: "GET",
dataType: "json",
url: '#Url.Action("GetData", "Report")',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function(xhr, status, error) {
alert(error);
}
});
}
Edit 2:
Changed to use Razor syntax so that this code will work with Razor/MVC3.

You are using MVC-2 syntax on Url.Action. This should work:
function Test() {
$.ajax(
{
url: '#Url.Action("GetData", "Report")',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (x, err, desc) {
alert(desc);
}
}
);
};

Because you are calling an action method that is returning a json object you can use the jQuery.getJSON() method.
<script type="text/javascript">
function Test() {
$.getJSON(
'#this.Url.Action("GetData", "Report")',
function (data) {
alert(data);
}
});
};
</script>

You may try jsaction too:
http://jsaction.codeplex.com

We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '#Url.Action("SubMenu_Click", "Home")?param1=value1 &param2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detail click here

Related

Redirect to another page after Ajax call?

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?
Here is the javascript/ajax code that gets called from a button being clicked.
#section scripts{
<script>
// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
},
});
});
</script>
}
For my code behind code that I am calling from the ajax call, that's below here:
public ActionResult OnPostCopyData (string accountid)
{
// Do my other stuff here
return RedirectToPage("Account_Information", new { id = account.Account_ID });
}
Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.
I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:
This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine
[HttpPost]
public ActionResult SubmitSomething()
{
return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}
And then this would be your Ajax request, I updated the success portion
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.redirectUrl !== undefined) {
window.location.replace(result.redirectUrl);
} else {
// No redirect found, do something else
}
},
});
});
This isn't tested, so I can only hope that it works for you right now
Edit: Updated the Url.Action to use OP's view names and parameters
Redirect to page returns a 301 response, which will be in the format:
HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp
To redirect after the ajax call you can redirect to the requested url by:
success: function (result) {
window.location = result.getResponseHeader('Location');
}

Pass null variable to MVC Controller

I want to pass a value (1) to my controller as you can see :
<input id="myButton2" type="button" value="Call Controller Method" onclick="myff('1');" />
Script:
function myff(re) {
$.getJSON('#Url.Action("MyControllerMethod","Reception",new { area ="Admin"})', function (data) {
refid = re;
});
}
Here is my controller
public JsonResult MyControllerMethod(string refid) {
return Json("Controller Method call", JsonRequestBehavior.AllowGet);
}
But when I clicked the button the action is fired but the refid in my action is null why ?
Instead of $.getJSON(), try this code:
function myff(re) {
$.ajax({
dataType: "json",
url: '#Url.Action("MyControllerMethod","Reception",new { area ="Admin"})',
data: {refid : re}
});
Note: Although $.getJSON() calls internally $.ajax() but the latter one gives you more flexibility- http://api.jquery.com/jQuery.getJSON/
You need to pass the value in the 2nd argument of $.getJSON()
var url = '#Url.Action("MyControllerMethod","Reception",new { area ="Admin"})';
$.getJSON(url, { refid: re }, function (data) {
console.log(data); // returns "Controller Method call"
});
I also recommend you use Unobtrusive Javascript rather than polluting markup with behavior
<input id="myButton2" type="button" data-x="1" value="Call Controller Method" />
$('#myButton2.click(function) {
var re = $(this).data('x');
$.getJSON(.....
});

How to call a function in another MVC controller using AJAX in Jquery

My folder structure looks like this. Both of these folders are contained within the Area folder.
I am trying to call a function from the EmailController inside ITRequests/Scripts/Edit.js and it fails to find it.
The .js code look likes this
$(document).on('change', '#StatusId', function (event) {
event.preventDefault();
debugger;
if(( $('#OldStatus').val() ) != ( $('#StatusId').val()) ) //Aka if the user switched the status on submit
{
var status_description = [$('#OldStatus').val(), $('#StatusId').val()];
$.ajax({
url: "/Email/Email/statusChangeEmail",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'request': $('#RequestId').val(), 'status_descriptions': status_description }),
done: function (data) {
debugger;
alert("working");
}
})
}
})
RequestId is a hidden value on the page which is being picked up correctly, likewise the status_description field is taking the correct values and (tries to) pass them to the function.
The function EmailController.cs is defined as such
[HttpPost]
public ActionResult statusChangeEmail(int request, string[] status_descriptions)
{
//stuff happens
return Json(1);
}
However every time this happens I get this error message
Why your URL is /Email/Email/statusChangeEmail? It should be /Email/statusChangeEmail.
The /Email means EmailController and /statusChangeEmail means controller action statusChangeEmail .

how to retrieve the returned value from the controller in the jsp using the ajax

this is my javascript code
<script type="text/javascript">
function callMe() {
var districtId = $("#district").val();
alert(districtId);
$.ajax({
type: "POST",
url: "addBranch",
data: "districtId=" + districtId,
success: function(response) {
}
});
}
</script>
this is my controller code
#RequestMapping(value = "/addBranch", method = RequestMethod.POST)
public #ResponseBody
List getForm1(#ModelAttribute Branch branch, Model model,#RequestParam("districtId")
int districtId) {
try {
districtVillageList = villageService.getDistrictVillageList(districtId);
} catch (Exception er) {
log.error("error in addLoanType=" + er);
}
return districtVillageList;
}
I am getting the list in the controller, but as i am new to ajax,i dont know how to retrieve the list in the ajax and use the retrieved values in jsp...Please can any one helo me??
As you have returned the list in the controller, just get in the response and iterate it using for-in loop
something like below,
<script type="text/javascript">
function callMe() {
var districtId = $("#district").val();
alert(districtId);
$.ajax({
type: "POST",
url: "addBranch",
data: "districtId=" + districtId,
success: function(response) {
for (var i in response){
// response[i].getterMethodHere
}
}
});
}
</script>
try using json objects to send the response instead of list. Learn More from jquery loop on Json data using $.each and jQuery loop over JSON result from AJAX Success?

Can't send array from jQuery to MVC 4 controller

I've googled this up and checked all over StackOverflow but I must be missing something... I have unobtrusive jQuery that hijaks a simple button click. It counts up the checkboxes and adds each checked boxes value to an array. The list is correct when I use an alert box in jQuery but the array never makes it to the controller side. The code flows to the controller but I break on var resolutionViewModel=new ResolutionViewModel(); and check trans - the argument is null. I'm new to jQuery and could really use the help here.
jQuery
// Return the selected transactions
function resolveTransactions() {
$('#btnResolve').click(function() {
var selectedTransactions = new Array();
$('input[name="chkTransaction"]:checked').each(function() {
selectedTransactions.push(this.value);
});
if (selectedTransactions.length > 0) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/AuditLog/Home/ResolutionFormDisplay',
contentType: 'application/json; charset=utf-8',
data: {trans : selectedTransactions},
traditional: true,
success: function (data) { alert(data); },
error: function(xhr, status, errorThrown) { alert("Error: " + errorThrown); }
});
}
});
};
Controller side
[HttpPost]
public PartialViewResult ResolutionFormDisplay(List<string> trans)
{
var resolutionViewModel = new ResolutionViewModel();
// fill Usernames dropdown selector in ViewModel
// fill Status dropdown selector in ViewModel
// fill list of transactionIds in ViewModel
return PartialView("_ResolutionDialog", resolutionViewModel);
}
Try having your controller accept a List, rather than just a single string (since you're not passing a single string):
[HttpPost]
public PartialViewResult ResolutionFormDisplay(List<string> value)
{
var resolutionViewModel = new ResolutionViewModel();
// fill Usernames dropdown selector in ViewModel
// fill Status dropdown selector in ViewModel
// fill list of transactionIds in ViewModel
return PartialView("_ResolutionDialog", resolutionViewModel);
}
Posted JSON needs to have named properties matching parameters in your controller method. Check the 'network' tab in Chrome dev tools and see exactly what you're posting, it's probably something like this:
"{\"value\":\"...\"}"
There is no value property to pass to your controller method's value parameter. I think the best would be just to get rid of the `JSON.stringify" and accept a list like Colin's answer, but if you want to take it as a string, the JSON string needs to be the value property of an object, not the other way around:
data: {value : JSON.stringify(selectedTransactions)},
Try passing your array as follows:
data:"{'trans':" + JSON.stringify(selectedTransactions)+"}"
Your method should be as follows:
public void Method(List<string> trans)
{
//Your implementation
}
SOLUTION:
The $.ajax postback was not sending properly formatted data to the controller. I discovered this by using the network tab in IE and looking at the Request Body of the POSTed http. It looked like this:transaction_table_length=10&chkTransaction=22&chkTransaction=23 -- It should have looked like this: {"trans":["22","23"]}. To solve this issue I stringified the property name and array as shown below, changed the dataType to 'text', and made the parameter on the controller action method take a String[] trans.
jQuery
// Return the selected transactions
function resolveTransactions() {
$('#btnResolve').click(function() {
var selectedTransactions = new Array();
$('input[name="chkTransaction"]:checked').each(function() {
selectedTransactions.push(this.value);
});
if (selectedTransactions.length > 0) {
$.ajax({
type: 'POST',
dataType: 'text',
url: 'http://localhost/AuditLog/Home/ResolutionFormDisplay',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ trans:selectedTransactions }),
traditional: true,
success: function (data) { alert(data); },
error: function(xhr, status, errorThrown) { alert(" Error: " + errorThrown); }
});
} else {
alert('You must select (check) at least one transaction to apply a resolution.');
return false;
}
return false;
});
};
MVC 4 controller action
[HttpPost]
public PartialViewResult ResolutionFormDisplay(string[] trans)
{
var resolutionViewModel = new ResolutionViewModel();
// fill Usernames dropdown selector in ViewModel
// fill Status dropdown selector in ViewModel
// fill list of transactionIds in ViewModel
return PartialView("_ResolutionDialog", resolutionViewModel);
}

Categories

Resources