AJAX Post to ASP.NET MVC Controller action method - Null parameters - c#

I want to post with AJAX a string array with some data to my controller. It's just plain text, and my controller is always receiving a null parameter. I understand i shouldn't stringify since i don't use a model or viewmodel.
I searched other questions but most refer to forms and use viewmodel properties.
Here is my code:
Controller
[HttpPost]
public ActionResult FirstAjax(string[] listValues)
{
//TODO
return Json("Reached the controller", JsonRequestBehavior.AllowGet);
}
I added that JSON return to check if I was actually hitting the controller and I receive the message on my view.
AJAX POST
var listValues = [];
listElements.each(function (index, element) {
listValues.push(element.innerText);
});
var serviceURL = '/Products/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: listValues,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
Since my list is sortable with drag & drop, the listValues is filled with the text value of the <li> items in the order when the button is clicked.
View
<div class="demo">
<ul id="sortable">
<li class="ui-state-default">Cat</li>
<li class="ui-state-default">Dog</li>
<li class="ui-state-default">Tiger</li>
</ul>
<button type="button" onclick="display_array();">Ajax Post!</button>
</div><!-- End demo -->

Write your Ajax POST method as follows:
$(document).ready(function(){
var listValues = [];
listElements.each(function (index, element) {
listValues.push(element.innerText);
});
var serviceURL = '/Products/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: {listValues: listValues},
contentType: 'application/json'
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
Hope this will solve your problem.

Change your ajax options to:
$.ajax({
...
data: {listValues: listValues},
...
});
the reason is: server is expecting a posted object/query string that's same naming with parameters. the data is converted to listValues=...&otherParams=... in query string. if you post an array without specifying parameter name, JQuery cannot map them correctly

You need contentType as application/json and use JSON.stringify to convert JavaScript object to JSON string.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: serviceURL,
data: JSON.stringify({ listValues: listValues}),
success: successFunc,
error: errorFunc
});

Related

MVC Ajax: How to send string from view to controller

I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}

grab value from checkboxes and post as list to controller

Check the code bellow. I am doing post a list of ProductId to my controller and wanted to receive it with view model called- UpdateProductStatus. but the problem with my current code is: ajax post it to controller successfully but the UpdateProductStatus cant grab any value of ProductId. This always returns null. Whats wrong i am doing here? Possibly in ajax i am doing wrong i think. How can i fix this to receive all ProductId as a list form controller? Thanks in advance
Controller:
[HttpPost]
public IActionResult UpdateProductStatus([FromBody]List<UpdateProductStatus> UpdateProductStatus)
{
return Json("ok");
}
View Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlexzWeb.ViewModels
{
public class UpdateProductStatus
{
public int ProductId { get; set; }
}
}
Jquery:
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push($(this).val());
});
for (var _allSelectedProductId in allSelectedProductId) {
allSelectedProductIdWithKey.push('ProductId'+':'+_allSelectedProductId);
}
console.log(allSelectedProductIdWithKey);
//var things = JSON.stringify(allSelectedProductIdWithKey);
var things = JSON.stringify({ 'UpdateProductStatus': allSelectedProductIdWithKey });
console.log(things);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
console.log('sssss');
},
failure: function (response) {
console.log('fffff');
}
});
Html:
<input type="checkbox" class="chkItems" value="1">
<input type="checkbox" class="chkItems" value="2">
<button id="btnActivate">Button</button>
Your current code is sending a payload like below for the ajax call.
{"UpdateProductStatus":["ProductId:0","ProductId:1"]}
Your action method argument is a list of UpdateProductStatus objects. So for model binding to work properly with your current action method parameter signature, your payload should be like below.
[{"ProductId":"1"},{"ProductId":"2"}]
There is no need to specify the parameter name. Just pass an array of items, each with a ProductId property and it's value.
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function () {
allSelectedProductIdWithKey.push({ ProductId: $(this).val() });
});
var things = JSON.stringify(allSelectedProductIdWithKey);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Products/AppendClientFilter',
data: things,
success: function (res) {
console.log('Successs', res);
},
failure: function (response) {
console.log('Error', response);
}
});
You can also remove the dataType in ajax call. jQuery ajax will guess the proper type from the response header and in your case you are going to return explicitly JSON.
To bind to your controller method, you need to send an array of objects containing a name/value pair for ProductId. To build your array of objects, use
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push({ ProductId: $(this).val() });
});
var things = JSON.stringify({ UpdateProductStatus: allSelectedProductId });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
....
});
});

How to serialize model, pass it to MVC controller in ajax request

I'm trying to pass my page's model to my controller for processing.
After processing the information, I want to update the div of id "savedText" to display "Billing Information saved successfully."
I have this in my view
function testingFunction() {
var obj = $('testForm').serialize();
$.ajax({
url: '#Url.Action("TestingFunction", "BuildGiftCard")',
dataType: 'json',
success: function (result) {
$("#savedText").html(result);
},
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(obj)
});
return false;
}
and I have this in my controller:
[HttpPost]
public JsonResult TestingFunction(PurchaseModel model)
{
return Json("Billing information saved successfully.");
}
what am I doing wrong?
When "inspecting element" in chrome, in the network tab, it's saying that my controller method isn't found.
Also, it's important for me to get the entire model from the view into the controller's function (TestingFunction in this case) so that I can get the form information and save it. I'm trying the .serialize() function but that results in obj = (empty string).
Three things:
$('testForm') should probably be $('.testForm') or $('#testForm'). As it is you're trying to select a <testForm></testForm>.
If you're just sending the form, it doesn't need to be json.
Try doing a post request:
$.ajax({
url: '#Url.Action("TestingFunction", "BuildGiftCard")',
dataType: 'json',
success: function (result) {
$("#savedText").html(result);
},
data: $('#testForm').serialize(),
type: 'POST'
});

use json data created via javascript with ajax.actionlink

I want to be able to post json data that was created via a javascript function through the Ajax.ActionLink helper.
I am able to accomplish this through straight jQuery code, but I am going to be doing this in a lot of places and wanted to see if there was a more efficient way to do it within MVC.
Working jQuery code:
$(function () {
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
});
});
Write a script that uses unobtrusive JavaScript hooks like data- attributes to store the settings.
HTML:
<div data-ajax-url='/Home/DeleteSelected'
data-ajax-post-data='{function name or json content}'>
....
</div>
JQuery Plugin
$(document).on("click","[data-ajax-url]", function(){
var postData = $(this).data("ajax-post-data");
var url = $(this).data("ajax-url");
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
}
If you are doing an ajax call and want to update html with MVC, I would normally return Partial View from my call.Then update the html of the current holder with the result
Server Side
public ActionResult DeleteSelected(int[] Ids)
{
//do something
MyModel model = new Model(); //create object with new data
return Partial("_PartialViewName", model);
}
Javascript
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'html',
data: postData
success: function(result){
$('#MyPartialViewContainer').html(result);
}
});
});

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

Categories

Resources