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

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

Related

ajax POST sending null

I originally wrote the call as a GET but found a limitation with the length of the URI. Ideally, the call will take an object and turns it into a JSON format string, then sends it to a controller which will encrypt that string. The controller will send back a true/false if it succeeded.
My problem with POST, once it reaches the controller, the data parameter set from the ajax is null.
Here is the ajax/js:
var encActionURL = '#Url.Action("Encrypt", "Home")';
$.ajax({
url: encActionURL,
type: "POST",
contentType: "application/json; charset=utf-8;",
dataType: "json",
async: true,
traditional: true,
data: { jsonDoc: JSON.stringify(jsonDataFile) },
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
Here is the controller:
[HttpPost]
public bool Encrypt(string jsonDoc)
{
return serverConnection.Encrypt();
}
Note that, when I simply change the type to 'GET', it works great but when the form gets too long, it throws a 414 status error.
Most of the fixes found that I seem to have is the 'application/json'. I've also set ajax to traditional.
After going through a rabbit-hole of security tokens and validating forms, it wasn't any of that... this might be a solution for anyone using ASP.NET Core 2.1 MVC (5?) or just in general. Could have been a syntax mistake, return type mistake, or a combination.
New Ajax
$.ajax({
url: encActionURL,
type: "POST",
data: { 'jsonDoc': JSON.stringify(jsonDataFile) }, // NOTICE the single quotes on jsonDoc
cache: false,
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
New Controller
[HttpPost]
public ActionResult EncryptJSON(string jsonDoc) // Switch to ActionResult, formerly JsonResult
{
return Json(serverConnection.Encrypt());
}

Ajax error when there's a parameter in url

I have a ajax code that fills a dropdownlist and I use mvc c#.
When I call to my method from ajax and I have an url in the directions bar without parameters the code works correctly, but if I have a parameter in url in the directions bar this not working and appears this error:
"{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}".
Here's my code:
$.ajax({
url:"../Records/myList",
type: "POST",
dataType: 'json',
contentType: 'application/json',
// data: JSON.stringify(Data),
success: function (resul) {
Function(resul);
},
error: function (message) {
}
});
My url: http://localhost:123/Record/EditRecord ->> so it's works
My other url: http://localhost:123/Record/EditRecord/1 ->> It does not work like this
Thanks in advance.
From given second URL (which doesn't work) I assume that you want to use jQuery AJAX with HttpGet method. The URL pattern matches this route:
http://localhost:123/{controller}/{action}/{id}
which id treated as UrlParameter.
Hence you need to use action argument & data representing URL parameter values, like this example:
Controller
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Alternatively a direct usage of URL parameter is applicable for GET methods without specifying data content:
View (JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB: Use jQuery.get for simplified version:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS: This is an example for HTTP POST request if you're looking for proper POST method with AJAX.
Controller
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Reference:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
i cant see any fault in the code but i suggest to try let the param come with it's name at server either if you choose to use data propery (of ajax function):
{key1: 'value1', key2: 'value2'}
or you use string query:
page?name=ferret&color=purple
bacuse you've just say that first method was work i assume there is no need to check POST/GET method.
EDIT:
be award to this.

Get ViewBag Data after $.ajax post success c# .net razor

I'm posting data with ajax and it's successfully posted. At the controller side I'm filling a ViewBag with data posted but i'm having a problem getting data from ViewBag.
Here's Ajax Code:
$.ajax({
type: "POST",
url: '../Home/getExistUsersFromJSON',
data: JSON.stringify({ jsonString: JSON.stringify(array) }),
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
// Alert that it was succesful!
var jsonList = '#Html.Raw(Json.Convert(ViewBag.newUsers))';
var jsList = JSON.parse(jsonList);
bootbox.dialog({
message: jsList,
title: "Utilisateurs",
buttons: {
success: {
label: "Success!",
className: "btn-success"
}
}
});
}
});
And this is the controller side
[ActionName("getExistUsersFromJSON")]
public void getExistUsersFromJSON(string jsonString)
{
IList<newUser> ctm =
new JavaScriptSerializer().Deserialize<IList<newUser>>(jsonString);
ViewBag.newUsers = ctm.ToList();
}
ViewBag is just an object that gets passed to the view when you render the page.
It doesn't make any sense to use that with AJAX; your server-side Razor code runs on initial server render only.
You need to server JSON as the response (using Json()).

getting data from controller in error function of jquery ajax -- Asp.net MVC

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

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

Categories

Resources