Passing a Var and List to Controller via Ajax - c#

I have a Text Box and a Select Options Multiple, i store all the selected items using knockout selectedOptions in a viewModel.
If I try to pass the captured information to my Controller using ajax I'm unable to recieve my MetricsChosenModel.
var MetricsChosenModel= window.vm.MetricsChosenModel();
var ApplicationsNameValue = $.trim($("#add-Applications").val());
if (ApplicationsNameValue.length <= 0) {
$("#text-add-Applications").popover('show');
}
$.ajax({
url: '/Admin/AddApplications',
type: "POST",
dataType: "JSON",
data: { ApplicationsName: ApplicationsNameValue, MetricsChosenModel: MetricsChosenModel },
success: function (returndata) {
if (returndata == true) {
}
else {
}
},
error: function () {
}
});
My Controller
public ActionResult AddApplications(string ApplicationsName,List<string> MetricsChosenModel)
{
//Code here
return View();
}
My MetricsChosenModel stores data in following format
MetricsChosenModel[0] => 5
MetricsChosenModel [1] => 6
why am i not able to recieve the list value of MetricsChosenModel , I'm able to recieve the ApplicationsName though,
Also it would be great if some one can explain, how am i wrong here,
Thanks,

Without knowing what your routing looks like, it's hard to pinpoint the exact source of the problem. If I had to guess, I'd say that you're getting the ApplicationsName value through the URL (routing or querystring parameter). If that's the case, you could probably add the [FromBody] attribute to the MetricsChosenModel. Note, however, that you're only allowed one FromBodyAttribute per method signature. If you need more variables, a simple solution to this problem is to create a model which contains each of the properties you're looking to receive in your controller action.
Hope that helps!

I've run into this problem myself with ASP.NET MVC: sending a model with some fields and one or more arrays up to a controller would not properly get the array contents into the C# model. The following change to the ajax call fixes it for me every time:
$.ajax({
url: '/Admin/AddApplications',
type: "POST",
contentType: 'application/json; charset=utf-8', // ADD THIS
dataType: "JSON",
data: JSON.stringify({ ApplicationsName: ApplicationsNameValue, MetricsChosenModel: MetricsChosenModel }), // Also added JSON.stringify
success: function (returndata) {
if (returndata == true) {
}
else {
}
},
error: function () {
}
});
The 'content-type' and 'JSON.stringify' help MVC with converting the model. Please let me know if that helped for you too :)

Related

How to get value from controller back to $.Ajax

My setup: asp.net mvc web app
I am having trouble getting a value from a controller back to the $.Ajax call (see below). The controller deletes a record in a database and counts some other records.
$.ajax({
type: "POST",
url: actions.action.RemoveItem + "?id=" + dataId,
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function (result) {
alert(result);
},
error: function (result) {
alert("Error");
}});
[HttpPost]
public JsonResult RemoveItem(int id)
{
... delete a record in the db
itemsCount = .... counts of some other records in the db
if (deletedRecord.id != null)
{
return Json(new { itemsCount });
}
else
{
return JsonError();
}
}
The ajax call and the controller work properly, however when I try to use the returned value in the success function, the alert(result) gives [object object].
I have looked through all related posts, but could not find a solution that worked. Could someone give me a hint where the problem could be and how to make it work?
Thank you in advance and regards, Manu
Result is a javascript object so alert works properly. If you want to alert it's structure as JSON use JSON.stringify() method like this:
alert(JSON.stringify(result));
If you want to access your itemsCount, just use dot or bracket notation:
alert(result.itemsCount);
alert(result['itemsCount']);

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

ajax call to c# mvc sends both post and get

I've looked at several solutions for making an ajax call and by not this issue mentioned anywhere i feel it might be something specific to the environment i'm working with.
My controller:
[HttpPost]
public ActionResult ChangeDefualtCC(string a)
{
return Json("ok");
}
[HttpGet]
public ActionResult ChangeDefualtCC()
{
return Json("ok");
}
JS:
$("nevermind").change(function () {
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
});
The Controller code is never hit, and this is what i'm seeing in chrome after the ajax call:
EDIT 2: The page hits the [HttpGet] method.
EDIT:
I tagged Ektron as well because it is used in the project, and it is possible that it is affecting the call.
My Routes:
Update: I have tried using Get, as well as Post, and also returning back to the View I was in, I get the 302 everytime.
any ideas?
It looks like it finds the "get" because you don't have a parameter in that call. I think you might be missing the content type from your ajax call, so the model binder cannot parse the content of your post as a parameter.
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
Your code seems to be absolutely correct.
This not be exact solution but try this may it work.
$("nevermind").change(function () {
$.post("/../Home/ChangeDefualtCC", { a: "A" }, function (data) {
console.log(data)
});
});
Our project is integrated with the CMS Ektron. We later discovered that Ektron is hit before the C# code, and has some affect to any url without a trailing url.
Thanks for all the help

Pass a collection to MVC controller via jquery

I'm using ASP.NET MVC3 with Jquery. I'm trying to pass my form elements back to the controller using something like this (Please note I removed success and error code for simplicity):
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: {collection: formElements},
success:
error:
dataType: "json"
});
My question is what should the parameter in my controller method look like:
Here is my controller method:
public ActionResult SubmitChanges(WHAT GOES HERE?)
{
}
So what I'm really looking for is what should be the type of the parameter going into the controller method? I want to be able to retrieve the values of the form elements in the controller.
So here is what I did. I have about 20-30 elements on my form so I really didn't want to have to turn each one into a parameter or list them all out in the collection.
In the jquery, I did the following:
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: { parms: formElements },
success:
error:
dataType: "json"
});
It then goes into my controller as a string:
public ActionResult SubmitChanges(string parms)
I then found a function to parse that string (seems to be working)
NameValueCollection qscoll = HttpUtility.ParseQueryString(parms);
This seems to work without listing out all of the form elements.
Assuming your form elements all correspond to your model (let's say it's MyModel), then it should simply be:
public ActionResult SubmitChanges(MyModel model)
{
}
MVC default model binding will do the rest :).
Make sure you change your data definition in the jQuery ajax method though, you've already serialized it. Just do:
data: formElements,
I'm assuming the following in your jQuery ajax method is a copy and paste error?
success:
error:
If it's not, then make sure you either remove it, or change them to:
success: function (result) {
//do something
},
error: function () {
//do something on error
}
The problem is that their is no model that corresponds to my form
elements.
Then you can have this:
public ActionResult SubmitChanges(int id, string name)
{
}
And then pass in the individual items:
var o = {
id = $("#id_elem_id").val(),
name = $("#name_elem_id").val()
}
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: JSON.stringify(o),
success:
error:
dataType: "json"
});
where id_elem_id and name_elem_id are the ids of your html elements. And add any additional parameters you need, just follow along.
You were almost there. Just get rid of the brackets around your data parameter:
var formElements = $('#myForm').serialize();
$.ajax({
type: 'POST',
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: formElements,
success: function(result) {
// handle the success of the AJAX request
},
error: function() {
// an error occurred
}
});

$.ajax POST/non post behaviour difference?

I am attempting to send some data via JSON to a MVC controller action:
For some reason, this works:
var items = [];
$("input:checked").each(function () { items.push($(this).val()); });
//This works
$.ajax({
type: "POST",
url: url,
data: { listofIDs: items, personID: personID},
dataType: "json",
traditional: true,
success: function() {
//Rebind grid
}
});
//This listofIDs is ALWAYS null !? (longhand for `$.getJSON` ?)
$.ajax({
url: url,
dataType: 'json',
data: { listofIDs: items, personID: personID },
success: function () {
//Rebind grid
}
});
So why does it work at the top, but the bottom it is always null? The same code is used to build items !?
edit: controller method
public ActionResult AddJson(List<int> listofIDs, int personID)
{
if (listofIDs==null || listofIDs.Count < 1)
return Json(false, JsonRequestBehavior.AllowGet);
...
//Add something to database
//Return true if suceeed, false if not
}
edit: so I ended up solving it by just turning the array into a string and sending it that way. That way I was able to send more than just the array variable.
var items = $(':input:checked').map(function () { return $(this).val();}).toArray();
var stringArray = String(items);
$.ajax({
url: url,
dataType: 'json',
data: { listOfIDs: stringArray, personID: personID },
success: function () {
//rebind grid
}
});
Note no POST type needed to be set.
Without type: "POST" it defaults to GET (according to the docs), which your server side code is probably not expecting.
Also, you could get a list of the values with...
var items = $(':input:checked').map(function() {
return $(this).val();
}).toArray();
jsFiddle.
Not sure if it's better though. Just an idea I had :)
The problem is probably on the server side. In the first case you are using HTTP POST in the other HTTP GET. That means that you probably have to access the data differently. Maybe have a look at Get individual query parameters from Uri for the HTTP GET case.
You're not specifying the type of the request, so it defaults to GET.
From jQuery Docs:
The type of request to make ("POST" or "GET"), default is "GET".
Perhaps you meant to specify POST. If you send it using GET the array will be added into the QUERY_STRING like ?listofIDs=... and won't be accessible the same way you normally access POSTed data.

Categories

Resources