MVC bind Json collection of objects to controller action - asp.net-mvc

is there a way to send a collection of objects to MVC action?
View:
$(".iconDocumentText").click(function (e) {
e.preventDefault();
var $inputs = $("form.form :input:not('.submit')");
var values = {}; // get search form values
$inputs.each(function () {
if ($(this).val()) {
values[this.name] = $(this).val();
}
});
console.log(JSON.stringify(values));
$.ajax({
url: "#Url.Action("Export","Log")",
data: JSON.stringify(values),
contentType: 'application/json',
type: 'GET',
success: function (data) {
.........
}
});
});
I tried this without any luck:
public ActionResult Export(Dictionary<string, string> values)
{
....
this is what's being sent to controller action:
{"f_device":"4","f_package":"AGI-VS-GAME-M52-1.5.3.2.67"}

You have also to indicate that it is of datatype json and pass them directly:
Script :
$.ajax({
url: "#Url.Action("Export","Log")",
data: values,
contentType: 'application/json',
type: 'GET',
dataType: 'json'
});
Controller :
public ActionResult Test(int f_device, string f_package)
{
EDIT :
But if you want to retrieve a dictionary, you can encapsulate your data in an object :
Script :
$.ajax({
url: "#Url.Action("Export","Log")",
data: { values : values },
contentType: 'application/json',
type: 'GET',
dataType: 'json'
});
Controller :
public ActionResult Test(Dictionary<string, string> values)
{

Related

.NET MVC - Ajax POST not calling .Net MVC method

I'm new to .NET MVC. I'm trying to make an Ajax call to a .NET method, but it doesn't work. Please help.
Here is my Ajax code:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "userID": $('#confirmation-email-userid').text().toString(), "subject": $('#confirmation-email-subject').text().toString() }),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
And here is my .Net method in UtilityController:
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail(string userID, string subject)
{
string destination = db.Users.Where(u => u.Id == userID).Select(u => u.Email).FirstOrDefault();
Task<string> result = new AccountController().SendEmailConfirmationTokenAsync(userID, subject, destination);
return Json(result, JsonRequestBehavior.DenyGet);
}
Try removing the quotation marks in the data parameters of the ajax request
Like this:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({
userID: $('#confirmation-email-userid').text().toString(),
subject: $('#confirmation-email-subject').text().toString()
}),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
Try this, but if you using asp.net mvc, i guess you don't need [WebMethod] attribute
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail([FromBody] MyModel model)
{
....
}
public class MyModel{
public string userID {get; set;}
public string string subject {get; set;}
}
I think issue with your url where in
use "url: "/Ultility/ResendConfirmationEmail","
insted of "url: "/Utility/ResendConfirmationEmail","
because your controller name is UtilityController
Do not use Webmethod in .net method
No need to use JSON.Stringify in ajax
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: "{'userID': "+$('#confirmation-email-userid').text().toString()+",'subject': "+$('#confirmation-email-subject').text().toString()+" }",
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
Remove the [webmothod] data annotation from your action method,
second option you are trying to pass json object for that u dont need to convert into string. Simply pass object
It wil work 👍

Controller Action cannot be called from $.Ajax javascript

In MVC, I have written an action in the controller for getting values. The action is as follows..
public void poolshapepdf(List<String> values)
{
...
}
To pass the parameter values to the controller action i pass the values from javascript..
the code is the below,
$.ajax({
type: 'POST',
url: rootDir + "IngroundCalculation/poolshapepdf",
data: { values: collectionPSElmt },
traditional: true,
});
Here collectionPSElmt is an array.
collectionPSElmt[index] = poolshapeValue[index] + "-" + psFeet[index] + "-" + psInch[index];
Here the issue is the controller action cannot be called from the javascript $.Ajax(..).
How do I fix this issue?
You calling the controller by POST and JSON data:
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
}
Now, make a proper call to your url.
specify the data type as json and always go for success function.
using that you can easily crack the report.
$.ajax({
url: '#Url.Action("poolshapepdf", "IngroundCalculation")',
type: "POST",
dataType: 'json',
data: collectionPSElmt ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Working..");
}
});
And at Controller Side,
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
// Your Code here....
}

Received parameter from ajax POST empty in controller + passed parameter in firebug MVC 4

I have looked over the net to figure out what my mistake is. All suggestions I found I tried, without any succes. I access the httppost action in my controller but the parameters stays empty.
AJAX function
var dataPost = { 'id': id, 'val': val };
debugger;
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: dataPost ,
contentType: 'json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
On debug DataPost is populated.
Controller
[HttpPost]
public ActionResult UpdateJson(string id, string val)
{
//do stuff
return Json(true);
}
The parameters I used in my controller have the same name as in my Ajax function. The format passed is json, I have also tried populating my data with:
var dataPost = { 'id': 'id', 'val': 'val' };
But this doesn't make any difference. I have also tried to work with a Class, like -->
Class
public class ScheduleData
{
public string id { get; set; }
public string val { get; set; }
}
Controller
public ActionResult UpdateJson(ScheduleData data)
{//Do something}
Any help would be appreciated. Thanks in advance
The format passed is json
No, not at all. You are not sending any JSON. What you do is
data: { 'id': id, 'val': val }
But as the documentation clearly explains this is using the $.param function which in turn uses application/x-www-form-urlencoded encoding.
So get rid of this contentType: 'json' property from your $.ajax call.
Or if you really wanna send JSON, then do so:
var dataPost = { 'id': id, 'val': val };
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: JSON.stringify(dataPost),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
Things to notice:
usage of JSON.stringify(dataPost) to ensure that you are sending a JSON string to the server
contentType: 'application/json' because that's the correct Content-Type value.

Post javascript module array as List object with ajax in asp .net mvc project

I want to send JavaScript object array as list object to server, the server side method(GetData) accepts list object with 3 elements, but all elements have null value. Any advice? Thanks in advance.
At Client:
User.js
define(function () {
function User(name) {
this.Name = name
}
return User;
});
main.js
var users = [new User('Barney'),
new User('Cartman'),
new User('Sheldon')];
$.ajax({
type: "POST",
url: "/Home/GetData",
data: {users: users},
success: function (data) {
//alert(data.Result);
},
dataType: "json"
});
At Server:
GetData action
public void GetData(List<User> users){
}
User Model
public class User {
public string Name { get; set; }
}
I changed main.js like below, and it worked:
main.js
var params = {'users': [new User('Barney'),
new User('Cartman'),
new User('Sheldon')]};
$.ajax({
type: "POST",
url: "/Home/GetData",
data: JSON.stringify(params),
success: function (data) {
//alert(data.Result);
},
contentType: "application/json"
});

ActionLink to HttpPost action method

I have this link on my page:
#Html.ActionLink("Like", "Like", "Like", new {likeId = i.ItemId}, new {id = #i.ItemId, #class = "likeButton"})
This is my ajax call:
$(document).on("click", ".likeButton", function (event) {
var itemId = event.target.id;
$.ajax({
url: this.href,
type: 'POST',
data: { item: itemId },
context: this,
success: function (result) {
...
return false;
});
And it works when action metohd is like:
public ActionResult Like(int itemId)
...
But if I decorate method with [HttpPost] It doesn't work.
Can this be achieved?
Also what security issue can be if I don't add [HttpPost]?
Try this:
$(document).on("click", ".likeButton", function (event) {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
...
return false;
});
You are passing item.Id twice, first in url and second in body. when using post method, you can still pass parameters through url. passing parameters with body is good when you want to hide these parameters.
And one more thing, you can use Ajax.ActionLink in this case (because it is created for this kind of cases)
And you have mistake:
data: { item: itemId }
Should be:
data: { itemId: itemId },

Resources