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
}
});
Related
This is my controller code :
[HttpPost]
public async Task<JsonResult> GetWebsite(int Id)
{
var website = await _uWebsitesService.GetWebsite(Id);
return (website == null ? this.Json("Website Not Found") : this.Json(website));
}
And this is my ajax :
$(".edit-website-btn").on("click", function () {
let id = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "/userpanel/GetWebsite/",
data: { Id: id },
dataType: "json",
contentType: "application/json",
success: function (result) {
console.log(result);
},
error: function (error) {
console.log(error);
},
})
})
When I check the result in console log, it's null when request type is post but when I change The ajax request and controller method to GET it returns the correct object.
this is because for your post method you are using application/json content that doesnt send id to an action, so action is using id=0 by default and can't get any data. Get action has a correct id and returns data. you can try to fix ajax for post by removing contentType: "application/json"
$.ajax({
type: "POST",
url: "/userpanel/GetWebsite/",
data: { Id: id },
dataType: "json",
.....
but imho better to use GET
$.ajax({
type: "GET",
url: "/userpanel/GetWebsite?id="+id,
dataType: "json",
...
and maybe you should try this too
let Id = $(this).data('id');
//or
let Id = this.getAttribute('data-id');
Your data parameter in the ajax call is an object, which just so happens to have a property called Id with the value you want.
However, your C# method expects just an integer, not an object with a property called "Id".
Simply change the JavaScript to only post the integer.
data: id,
To also help out C#'s binding, you should also specify that the parameter is from the request's body. This is techinally optional, but might help with maintainability and ensuring your value doesn't accidently come in from another source (like a rouge query param).
public async Task<JsonResult> GetWebsite([FromBody] int Id)
If you need to pass more than one value in the POST call, you'll need to make a class in C# and bind that instead of the int.
I have a jquery ajax script like following
$.ajax({
type: "POST",
url: "Main/receive", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'p':$("#txtname").val() }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
And I am calling to Controller action method. The data is sending to the controller's action method and I am also receiving data from the controller. But the data that I am receiving is inside the error function of jquery ajax.
I want it to be inside the success function.
Why my success function is not getting called.
Following is my controller's action method,
[HttpPost]
public string receive(string p)
{
ViewBag.name = p;
return p;
}
The reason for the error is that you have specified that the returned data type be json (in the line dataType: "json",) but you method returns text. You have 2 options.
Change the controller method to return json using return Json(p);
Change the ajax option to dataType: "text", or just omit it
However you can improve your script as noted below
$.ajax({
type: "POST",
url: '#Url.Action("receive", "Main")', // don't hardcode url's
data: { p: $("#txtname").val() }, // no need to stringify (delete the contentType: option)
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
or even simpler
$.post('#Url.Action("receive", "Main")', { p: $("#txtname").val() }, function(result) {
alert('Yay! It worked!');
}).fail(function(result) {
alert('Oh no zzzz:('+result.responseText);
});
Notes: You should always use #Url.Action() to generate the correct urls, and it is not necessary in this case to stringify the data (but you need to remove the contentType: line so it used the default application/x-www-form-urlencoded; charset=UTF-8)
In addition, this is not strictly a POST (your not changing data on the server - but I assume this is just for testing). And there is no point in the line ViewBag.name = p; - it does nothing in your context, and as soon as you return from the method, ViewBag is lost anyway.
try to change your controller code as follows
[HttpPost]
public ActionResult List(string p)
{
ViewBag.name = p;
return Json(ViewBag);
}
Your controller method should look like this:
[HttpPost]
public ActionResult receive(string p)
{
return Json(p);
}
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'
});
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 :)
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.