Pass null variable to MVC Controller - javascript

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(.....
});

Related

Ajax passing data to ASP.NET controller

I'm attempting to run an ajax request on my ASP.NET web app where I pass a search term and receive some data back
<div class="form-group">
<input type="text" id="orgSearch" placeholder="Search organisation by name..." class="form-control" name="search" autocomplete="off" data-controller="#Model.ControllerName" data-target-property="#Model.LookaheadProperty">
</div>
<script>
$(document).ready(function () {
var form = document.getElementById("orgSearch");
form.addEventListener("keyup", function (event) {
event.preventDefault();
var search = document.getElementById("orgSearch").value;
$.ajax({
type: "GET",
url: "Organisation/Search?search=" + search,
success: function (object) {
console.log(object);
}
});
});
});
</script>
And then here's the method in my OrganisationsController.cs class
public class OrganisationsController : Controller
{
[HttpGet]
public async Task<IActionResult> Search([FromRoute] string search)
{
var items = await _organisationsService.SearchAsync(search);
return Ok(items);
}
}
However, when I try it the ajax call isn't even being made (It's generating a 404 error on the console log) and I can't work out how to pass the search parameter. Does anyone have any suggestions?
Fix ajax url from organization to organizations and add "/" in the beginning:
url: "/Organisations/Search?search=" + search,
your action then
public async Task<IActionResult> Search([FromQuery] string search)
{
......
}
You can also try to use [FromUri] instead [FromQuery]
And by the way, if your version Mvc supports attribute routing, it maybe better to change action to this:
[Route("~/Organizations/Search/{search}")]
public async Task<IActionResult> Search( string search)
{
....
}
in this case your ajax url:
url: "/Organisations/Search/" + search,

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');
}

ajax get boolean value from C# function T4MVC

I have a research bar on my website, the code for it is the following:
<form onsubmit="return IsValidCustomer()">
<input class=" sb-search-input" placeholder="Chercher un client..." type="text" value="" name="search" id="search">
<input class="sb-search-submit" type="submit" value="" id="submit-search">
<span class="sb-icon-search"></span>
</form>
As you see, it calls a javascript function:
function IsValidCustomer() {
var name = document.getElementById('search').value;
$.ajax({
type: 'GET',
url: lookForCustomerUrl,
data: {'name' : name },
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (e) {
alert(e.value);
}
});
return false;
}
Which will call my c# function, to see if the customer I'm looking for actually exist. If it does, for the moment, I just want to show the result, which is suppose to be True or False. But I'm only getting the error alert...
Here's my C# code, in my controller:
public virtual bool LookIfCustomerExist(string name)
{
List<Customer> customers = SearchClient(name);
bool returnedValue = customers.Count != 0;
return returnedValue;
}
The SearchClient function you see is working fine and the returned boolean is correct.
Thanks for help... I just want to save a unnecessary page...
When you make an ajax call from an aspx page to a method in the code-behind, you need to decorate the method with an attribute [Webmethod].Also, it needs to be a static method. That means, you would also need to change 'SearchClient' to a static method if it isn't so.
[Webmethod]
public static virtual bool LookIfCustomerExist(string name)
{
List<Customer> customers = SearchClient(name);
bool returnedValue = customers.Count != 0;
return returnedValue;
}

Returning view from jQuery AJAX get operation

I'm trying to make an asynchronous jQuery get to an MVC Action to return a view. For some reason, although it accesses the action, it does not render the view.
This is the jQuery:
function showArchive(url) {
var moreRecentThanDate = $("#chooseDate").val();
$.get(url, { moreRecentThan: moreRecentThanDate });
}
and this is the action :
[HttpGet]
public ActionResult ShowArchive(DateTime moreRecentThan)
{
List<NewIndexViewModel> model = Service.GetArchives(moreRecentThan);
ViewBag.IsArchive = true;
return View("Index", model);
}
PS: I call this jQuery from an ad-hoc modal popup;
You should attach the result in somewhere using a syntax like that:
$.get(url, { moreRecentThan: moreRecentThanDate }).done(function(data) {
$('.result').html(data);
)};
When in doubt, check the jQuery documentation, get(), the second last example is what you want, I believe..
$.get(url, { moreRecentThan: moreRecentThanDate })
.done(function(data) {
$('#myElem').append(data);
// or $('#myElem').html(data);
});
Jquery Part
$.get( url, { moreRecentThan: moreRecentThanDate }, function(data) {
// callback or response
$('#details_Div').replaceWith(data);
});
where the user controller has an action named details that does:
public ActionResult Details( int id )
{
//create a model
return PartialView( "UserDetails", model );
}
PartialView is important here.
This is assuming that your partial view is a container with the id detailsDiv so that you just replace the entire thing with the contents of the result of the call.
UserDetails partial view
http://evolpin.wordpress.com/2011/04/26/asp-net-mvc-partial-view-and-ajax-real-world-example/
<div id="details_Div">
<HTML will be replaced once the ajax is completed>
</div>

call controller action from .cshtml page with jquery

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

Categories

Resources